12.18 aop身份验证
对所有卖家页面进行身份验证,采用aop编程
步骤:1.获得request
2.查询cookie
3.查询redis
4.查询不通过时,采用抛出异常,捕捉异常,再异常里加入跳转到登陆页面的方法
准备工作:
创建异常方法,可以不添加内容
1
2
|
public class SellerAuthorizeException extends RuntimeException { } |
aop编程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
@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() { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); //查询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(); } } } |
登陆异常异常捕捉并加入跳转方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
@ControllerAdvice public class SellExceptionHandler { @Autowired private ProjectUrlConfig projectUrlConfig; //拦截登录异常 //http://sell.natapp4.cc/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" )); } } |