首先咱們定義一個切入點(匹配com.ed.controller.Seller開頭的controller的全部public方法)前端
@Pointcut("execution(public * com.ed.controller.Seller*.*(..))") public void checkToken() {}
而後在進入這些方法以前進行token校驗redis
@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進行攔截,並返回自定義的對象給前端cookie
@ControllerAdvice public class SellExceptionHandler {
@ExceptionHandler(value = SellerAuthorizeException.class) @ResponseBody public ResultVO handlerSellerException(SellerAuthorizeExceptione) { return ResultVOUtil.error(e.getCode(), e.getMessage()); } }
CookieUtil方法spa
/** * 獲取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; }