希望访问到每个url时都需进行用户信息的认证。所以使用AOP方式作为切面,通过获取request 查询cookie 查询redis。
如果查询不通过,不是直接跳转,而是抛出异常,并捕获进行相关处理。
二、异常(查询不通过时捕获):
具体代码实现如下:
一、校验
@Aspect @Component @Slf4j public class SellerAuthorizeAspect { @Autowired private StringRedisTemplate redisTemplate; //切入点 , 排除登录和登出的操作 @Pointcut("execution(public * com.imooc.controller.Seller*.*(..))" + "&& !execution(public * com.imooc.controller.SellerUserController.*(..))") public void verify() { } @Before("verify()") public void doVerify() { //1.获取httprequest ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); //2.查询cookie Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN); //如果为空,表示未登录 if (cookie == null) { log.warn("【登录校验】Cookie中查不到token"); throw new SellerAuthorizeException(); } //去redis里查询 String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue())); if (StringUtils.isEmpty(tokenValue)) { log.warn("【登录校验】Redis中查不到token"); throw new SellerAuthorizeException(); } } }
二、异常(查询不通过时捕获):
@ControllerAdvice public class SellExceptionHandler { @Autowired private ProjectUrlConfig projectUrlConfig; //拦截登录异常,未登录状态时调到登录页 //http://sell.natapp4/sell/wechat/qrAuthorize?returnUrl=http://sell.natapp4.cc/sell/seller/login //注:授权地址和登录地址可以不一样 @ExceptionHandler(value = SellerAuthorizeException.class) public ModelAndView handlerAuthorizeException() { return new ModelAndView("redirect:" //授权地址 .concat(projectUrlConfig.getWechatOpenAuthorize()) .concat("/sell/wechat/qrAuthorize") .concat("?returnUrl=") .concat(projectUrlConfig.getSell()) //登录地址 .concat("/sell/seller/login")); } }