使用AOP进行权限验证
首先我们定义一个切入点(匹配com.ed.controller.Seller开头的controller的所有public方法)
@Pointcut("execution(public * com.ed.controller.Seller*.*(..))") public void checkToken() {}
然后在进入这些方法之前进行token校验
@Before("checkToken()") public void check() { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); //查询cookie Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN); if (cookie == null) { log.warn("【token校验】Cookie中查不到token"); throw new SellerAuthorizeException(ResultEnum.TOKEN_ERROR); } //去redis里查询 String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue())); if (StringUtils.isEmpty(tokenValue)) { log.warn("【token校验】Redis中查不到token"); throw new SellerAuthorizeException(ResultEnum.TOKEN_ERROR); } }
抛出的异常可定义一个handler进行拦截,并返回自定义的对象给前端
@ControllerAdvice public class SellExceptionHandler {
@ExceptionHandler(value = SellerAuthorizeException.class) @ResponseBody public ResultVO handlerSellerException(SellerAuthorizeExceptione) { return ResultVOUtil.error(e.getCode(), e.getMessage()); } }
CookieUtil方法
/** * 获取cookie * @param request * @param name * @return */ public static Cookie get(HttpServletRequest request, String name) { Map<String, Cookie> cookieMap = readCookieMap(request); if (cookieMap.containsKey(name)) { return cookieMap.get(name); }else { return null; } } /** * 将cookie封装成Map * @param request * @return */ private static Map<String, Cookie> readCookieMap(HttpServletRequest request) { Map<String, Cookie> cookieMap = new HashMap<>(); Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie: cookies) { cookieMap.put(cookie.getName(), cookie); } } return cookieMap; }