使用AOP进行权限验证 ​

时间:2023-05-17

首要咱们定义一个切入点(匹配com.ed.controller.Seller最初的controller的所有public办法)
@Pointcut(“execution(public*com.ed.controller.Seller*.*(..))”)publicvoidcheckToken(){}
然后在进入这些办法之前进行token校验
@Before(“checkToken()”)publicvoidcheck(){
ServletRequestAttributesattributes=(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletRequestrequest=attributes.getRequest();//查询cookieCookiecookie=CookieUtil.get(request,CookieConstant.TOKEN);if(cookie==null){
log.warn(“【token校验】Cookie中查不到token”);thrownewSellerAuthorizeException(ResultEnum.TOKEN_ERROR);
}//去redis里查询StringtokenValue=redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX,cookie.getValue()));if(StringUtils.isEmpty(tokenValue)){
log.warn(“【token校验】Redis中查不到token”);thrownewSellerAuthorizeException(ResultEnum.TOKEN_ERROR);2024澳门原料网1688白老虎
}
}
抛出的异常可定义一个handler进行拦截,并回来自定义的对象给前端
@ControllerAdvicepublicclassSellExceptionHandler{
@ExceptionHandler(value=SellerAuthorizeException.class)
@ResponseBodypublicResultVOhandlerSellerException(SellerAuthorizeExceptione){returnResultVOUtil.error(e.getCode(),e.getMessage());
}
}
CookieUtil办法
/***获取cookie
*@paramrequest
*@paramname
*@return*/publicstaticCookieget(HttpServletRequestrequest,
Stringname){
MapcookieMap=readCookieMap(request);if(cookieMap.containsKey(name)){returncookieMap.get(name);
}else{returnnull;
}
}/***将cookie封装成Map
*@paramrequest
*@return*/privatestaticMapreadCookieMap(HttpServletRequestrequest){
MapcookieMap=newHashMap<>();
Cookie[]cookies=request.getCookies();if(cookies!=null){for(Cookiecookie:cookies){
cookieMap.put(cookie.getName(),cookie);
}
}returncookieMap;
}

文章标签:

Copyright © 2016 2024澳门原料网1688白老虎,保留所有权利。 粤ICP备09033321号

2024澳门原料网1688白老虎 2024澳门原料网1688白老虎
2024澳门原料网1688白老虎
扫描二维码
与项目经理交流
2024澳门原料网1688白老虎 2024澳门原料网1688白老虎
2024澳门原料网1688白老虎
扫描二维码
与项目经理交流
2024澳门原料网1688白老虎
ciya68