A设备向服务器请求getLoginCode接口,这个接口根据请求的sessionId进行base64或其他加密方式进行加密,然后以此作为二维码的值,并将这个loginCode写到redis里,设置5分钟过期。然后将这个loginCode返回给A设备,A设备以此值来生成登陆的二维码。
B设备来扫A设备的二维码的时候,携带二维码的值,请求授权登陆的接口scanConfirmLogin,此接口里先校验二维码是否过期,没过期的话进行后面的业务逻辑处理,将用户的基本信息和token写到redis里。
/** * 获取扫描登陆的二维码 * @param noncestr随机字符串 * @throws Exception */ @RequestMapping(value = "user/getLoginCode.json") public void getLoginCode(String noncestr,HttpServletRequest request,HttpServletResponse response) throws Exception { if(StringUtil.isBlank(noncestr)){ apiData(request, response,ReqJson.error(CommonError.PARAMS_IMPERFECT)); return; } //参数的有效性校验在拦截器里实现 int expirationTime=300; //时效5分钟 final String sessionId=request.getSession().getId(); String loginCode=ToolUtils.getBase64(sessionId); JedisUtil.set(loginCode, loginCode, expirationTime); Map<String,Object> map=new HashMap<>(); map.put("loginCode", loginCode); map.put("expirationTime", expirationTime); apiData(request, response, ReqJson.ok(map)); } /** * 扫码确认登陆 * @param loginCode * @param request * @param response * @throws Exception */ @RequestMapping(value = "user/scanConfirmLogin.json") @AuthorizationApi public void scanConfirmLogin(@CurrentToken final Token token,String loginCode,HttpServletRequest request,HttpServletResponse response) throws Exception { if(StringUtil.isBlank(loginCode)){ apiData(request, response,ReqJson.error(CommonError.PARAMS_IMPERFECT)); return; } String userId=token.getUserId(); Map<String,String> map=new HashMap<>(); String loginTicket=JedisUtil.get(loginCode); if(StringUtil.isBlank(loginTicket)){ //二维码过期 apiData(request, response,ReqJson.error(CommonError.TWO_DIMENSIONAL_CODE_HAS_EXPIRED)); return; } UserInfo userInfo = userInfoBiz.getUser(new UserInfo(userId)); if(userInfo==null){ apiData(request, response,ReqJson.error(UserError.USER_NOT_FOUND)); return; } //将用户信息放在缓存中 map.put(BaseConfig.ACCESS_TOKEN, token.getAccessToken()); map.put("userId", userInfo.getUserId()); map.put("rongCloudToken", userInfo.getRongCloudToken()); map.put("identity", userInfo.getIdentity()); JedisUtil.setMap(loginCode+"scanConfirmLogin", map, 300); apiData(request, response, ReqJson.ok(new Object())); } /** * 获取登陆状态 * @param loginCode * @param request * @param response * @throws Exception */ @RequestMapping(value = "user/getScanConfirmLoginStatus.json") public void getLoginStatus(final String loginCode,HttpServletRequest request,HttpServletResponse response) throws Exception { if(StringUtil.isBlank(loginCode)){ apiData(request, response,ReqJson.error(CommonError.PARAMS_IMPERFECT)); return; } Map<String,String> map= JedisUtil.getMap(loginCode+"scanConfirmLogin"); if(map==null){ apiData(request, response,ReqJson.error(CommonError.AUTHORIZATION_HAS_EXPIRED)); return; } apiData(request, response, ReqJson.ok(map)); }