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

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值