② 将授权后跳转的地址改为登录地址
//用户授权同意后回调的地址,从请求参数中获取code
@GetMapping("/qrUserInfo")
public String qrUserInfo(@RequestParam("code") String code) {
WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
try {
//通过code获取access_token
wxMpOAuth2AccessToken = wxOpenService.oauth2getAccessToken(code);
} catch (WxErrorException e) {
log.error("【微信网页授权】{}", e);
throw new SellException(ResultEnum.WECHAT_MP_ERROR.getCode(), e.getError().getErrorMsg());
}
//从token中获取openid
String openId = wxMpOAuth2AccessToken.getOpenId();
//授权成功后跳转到卖家系统的登录地址
String returnUrl = "http://heng.nat300.top/sell/seller/login";
log.info("openid={}", openId);
return "redirect:" returnUrl "?openid=" openId;
}
③ 在浏览器请求这个链接:https://open.weixin.qq.com/connect/qrconnect?appid=wx6ad144e54af67d87&redirect_uri=http://sell.springboot.cn/sell/qr/oTgZpwenC6lwO2eTDDf_-UYyFtqI&response_type=code&scope=snsapi_login&state=http://heng.nat300.top/sell/wechat/qrUserInfo
第三应用请求使用微信扫码登录,而不是使用本网站的密码:
用户同意授权后登入第三方应用的后台管理系统:
4. Spring AOP校验用户有没有登录
@Aspect
@Component
@Slf4j
public class SellerAuthorizeAspect {
@Autowired
private StringRedisTemplate redisTemplate;
@Pointcut("execution(public * com.hh.controller.Seller*.*(..))"
"&& !execution(public * com.hh.controller.SellerUserController.*(..))")
public void verify() {}
@Before("verify()")
public void doVerify() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//查询cookie
Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
//如果cookie中没有token说明已经登出或者根本没有登录
if (cookie == null) {
log.warn("【登录校验】Cookie中查不到token");
//校验不通过,抛出异常
throw new SellerAuthorizeException();
}
//去redis里查询
String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
//如果redis中没有对应的openid,同样表示登出或者根本没有登录
if (StringUtils.isEmpty(tokenValue)) {
log.warn("【登录校验】Redis中查不到token");
throw new SellerAuthorizeException();
}
}
}
5. 拦截登录校验不通过抛出的异常
拦截及登录校验不通过的异常,让其跳转到登录页面,扫码登录
@ControllerAdvice
public class SellExceptionHandler {
//拦截登录异常
@ExceptionHandler(value = SellerAuthorizeException.class)
public ModelAndView handlerAuthorizeException() {
//拦截异常后,跳转到登录界面
return new ModelAndView("redirect:".concat("https://open.weixin.qq.com/connect/qrconnect?"
"appid=wx6ad144e54af67d87"
"&redirect_uri=http://sell.springboot.cn/sell/qr/"
"oTgZpwenC6lwO2eTDDf_-UYyFtqI"
"&response_type=code&scope=snsapi_login"
"&state=http://heng.nat300.top/sell/wechat/qrUserInfo"));
}
@ExceptionHandler(value = SellException.class)
@ResponseBody
public ResultVO handlerSellerException(SellException e) {
return ResultVOUtil.error(e.getCode(), e.getMessage());
}
@ExceptionHandler(value = ResponseBankException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
public void handleResponseBankException() {
}
}
,来源:hengheng.blog.csdn.net/article/details/107823201