A企业和B企业要进行合作时,A要开放api接口给B调用,这时候A可以采用基于accessToken的方式实现开放api接口
数据库表设计
B调用方式
B企业调用接口前先获取accessToken
http://localhost:8080/auth/getAccessToken?appId=123456&appSecret=a1b2c3
然后调动真正的业务方法时携带accessToken
http://localhost:8080/openApi/getUser?accessToken=ac18deb132684f6c8cb2c01bd85f86aa
A企业具体实现
A企业设置accessToken过期时间为2小时,并且启动一个job定时刷新
A企业在拦截器里拦截所有的开放api接口,验证accessToken是否存在,是否过期,如果accessTokne存在并且没有过期就可以继续执行业务方法
@Component public class AccessTokenInterceptor extends BaseApiService implements HandlerInterceptor { @Autowired private BaseRedisService baseRedisService; public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { System.out.println("---------------------开始进入请求地址拦截----------------------------"); String accessToken = httpServletRequest.getParameter("accessToken"); // 判断accessToken是否空 if (StringUtils.isEmpty(accessToken)) { // 参数Token accessToken resultError(" this is parameter accessToken null ", httpServletResponse); return false; } String appId = (String) baseRedisService.getString(accessToken); if (StringUtils.isEmpty(appId)) { // accessToken 已经失效! resultError(" this is accessToken Invalid ", httpServletResponse); return false; } // 正常执行业务逻辑... return true; } public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { System.out.println("--------------处理请求完成后视图渲染之前的处理操作---------------"); } public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { System.out.println("---------------视图渲染之后的操作-------------------------0"); } // 返回错误提示 public void resultError(String errorMsg, HttpServletResponse httpServletResponse) throws IOException { PrintWriter printWriter = httpServletResponse.getWriter(); printWriter.write(new JSONObject().toJSONString(setResultError(errorMsg))); } }
项目结构:
github下载地址:https://github.com/jake1263/openApi