美文网首页
Spring Boot使用自定義註解和攔截器進行權限控制

Spring Boot使用自定義註解和攔截器進行權限控制

作者: Kris_Wilson | 来源:发表于2017-12-25 16:53 被阅读0次

最近工作中需要在微信管理端的應用中使用自定義註解實現權限控制,必須保持和後台權限一致,因為賬戶系統分為partner、alliance、merchant三種,頁面和權限也分為三套所以微信後台也要分別對著三種權限進行控制。

实现HandlerInterceptor

public class AuthenticationInterceptor extends HandlerInterceptorAdapter{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 将handler强转为HandlerMethod, 前面已经证实这个handler就是HandlerMethod
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 从方法处理器中获取出要调用的方法
        Method method = handlerMethod.getMethod();
        // 获取出方法上的RequiresPermissions注解
        RequiresPermissions permissions = method.getAnnotation(RequiresPermissions.class);
        if (permissions == null) {
            // 如果注解为null, 说明不需要拦截, 直接放过
            return true;
        }
        
        String accountType = SessionUtil.getAccountType(request);
        // 获取用户所有权限
        Set<String> permsSet = SessionUtil.permissions(request, response);
        String[] values = null;
        if (accountType.equals(USER_TYPE.PARTNER.key)) {
            values = permissions.partner();
        } else if (accountType.equals(USER_TYPE.ALLIANCE.key)) {
            values = permissions.alliance();
        } else if (accountType.equals(USER_TYPE.MERCHANT.key)) {
            values = permissions.merchant();
        }
        
        if (values.length > 0) {
            // 权限列表为空
            if (permsSet.size() == 0) {
                if (SessionUtil.isSuperAdmin(request.getSession())) {
                    // 如果是超级管理员
                    return true;
                } else {
                    return false;
                }
            }
            for (String permission : values) {
                if (!permsSet.contains(permission)) {
                    return false;
                }
            }
        }
        
        // 拦截之后应该返回公共结果, 这里没做处理
        return true;
    }
}

配置拦截器

@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter{
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // TODO Auto-generated method stub
        registry.addInterceptor(new AuthenticationInterceptor()).addPathPatterns("/**");
    }
}

自定义权限注解

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequiresPermissions {
    String[] partner() default {};
    String[] alliance() default {};
    String[] merchant() default {};
}

參考文章:SpringBoot使用自定义注解实现权限拦截

相关文章

网友评论

      本文标题:Spring Boot使用自定義註解和攔截器進行權限控制

      本文链接:https://www.haomeiwen.com/subject/gwblgxtx.html