实现自定义权限控制(Springboot+拦截器+注解)

mac2024-05-18  31

1、定义权限常量 Constants.java

public class Constants { public static final String FRANCHISEE_TYPE_MAIN = "MAIN"; public static final String FRANCHISEE_TYPE_ADMIN = "ADMIN"; }

2、定义权限的注解 PermissionCheck

@Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface PermissionCheck { //自定义角色值,如果是多个角色,用逗号分割。 String role(); }

3、权限拦截器 AuthorityInterceptorAdapter

@Slf4j @Component public class AuthorityInterceptorAdapter extends HandlerInterceptorAdapter { @Autowired private ITokenService tokenService; @Autowired private IFranchiseeInfoService franchiseeInfoService; /** * 拦截所有请求验证是否登录 * * @param request * @param response * @param handler * @return * @throws Exception */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler instanceof HandlerMethod) { String token = null; // 获取请求中的token Cookie[] cookies = request.getCookies(); if (cookies == null || cookies.length <= 0) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); throw new ServiceException(ErrorCode.authority_un_login.getCode(), ErrorCode.authority_un_login.getMessage()); } for (Cookie cookie : cookies) { if (Constants.HEADER_ACCESS_TOKEN_KEY.equals(cookie.getName())) { token = cookie.getValue(); } } if (token == null) { log.error("当前未登录"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); throw new ServiceException(ErrorCode.authority_un_login.getCode(), ErrorCode.authority_un_login.getMessage()); } // 判断是否登录 boolean isLogin = tokenService.validateToken(token); if (!isLogin) { log.error("当前未登录"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); throw new ServiceException(ErrorCode.authority_un_login.getCode(), ErrorCode.authority_un_login.getMessage()); } TokenModel tokenModel = tokenService.getTokenModelByToken(token); //授权成功,判断登录角色 // 获取方法上的注解 PermissionCheck requiredPermission = handlerMethod.getMethod().getAnnotation(PermissionCheck.class); // 如果方法上的注解为空 则获取类的注解 if (requiredPermission == null) { requiredPermission = handlerMethod.getMethod().getAnnotation(PermissionCheck.class); } // 如果标记了注解,则判断权限 if (requiredPermission != null && StringUtils.isNotBlank(requiredPermission.role())) { List<String> roleList = Arrays.asList(requiredPermission.role().split(",")); // redis或数据库 中获取该用户的权限信息 并判断是否有权限 String permissionString = tokenModel.getUserType(); if (!roleList.contains(permissionString)) { throw new ServiceException(ErrorCode.authority_has_false_permission.getCode(), ErrorCode.authority_has_false_permission.getMessage()); } else { return super.preHandle(request, response, handler); } } else { throw new ServiceException(ErrorCode.authority_has_false_permission.getCode(), ErrorCode.authority_has_false_permission.getMessage()); } } return super.preHandle(request, response, handler); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { BaseContextCommand.remove(); super.afterCompletion(request, response, handler, ex); } }

4、拦截器注入配置

@Configuration public class WebConfigurer implements WebMvcConfigurer { @Autowired private AuthorityInterceptorAdapter authorityInterceptorAdapter; @Autowired private OmsProperties omsProperties; /** * 配置接口授权验证拦截器 * * @param registry */ @Override public void addInterceptors(InterceptorRegistry registry) { // 配置不需要拦截的url List<String> patterns = Arrays.asList(omsProperties.getUncheckList().split(";")); registry.addInterceptor(authorityInterceptorAdapter).addPathPatterns("/**") .excludePathPatterns(patterns); } }

 

最新回复(0)