springsecurity自定义角色权限授权

security自定义角色权限

通过注解标记controller的方式与config配置的方式过于繁琐。这样每写一个接口都要去写这个注解,关键还要记相对应的权限,根本不符合当前的开发。

    //注解方式
    @PreAuthorize("hasAuthority('test')")
    public RespBean test(){
        ....
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
         http
            .authorizeRequests()
            .antMatchers("/login","/logout").hasAuthority("test");
    }

在过滤器链中FilterSecurityInterceptor负责权限的效验,所以从这个过滤器来展开

①对角色权限进行设置
通过阅读源码发现FilterSecurityInterceptord通过调用SecurityMetadataSource子类对象的getAttributes方法拿到Collection集合这里面的ConfigAttribute对象就是角色权限所以我们可以通过实现SecurityMetadataSource对象自定义设置角色权限。

我们实现SecurityMetadataSource对象的子接口后,重写getAttributes方法自定义需要设置的角色权限。

    @Component
    public class CustomFilter implements FilterInvocationSecurityMetadataSource {
        @Autowired
        private IMenuService menuService;

        AntPathMatcher antPathMatcher=new AntPathMatcher();

        @Override
        public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
            //获取请求的url
            String requestUrl = ((FilterInvocation) o).getRequestUrl();
            List<Menu> menus=menuService.getMenusWithRole();
            for (Menu menu:menus) {
                //判断请求的url是否在菜单角色是否匹配
                //访问菜单(访问的url地址reuqestUrl)与之匹配上的菜单,此菜单所能够访问的角色返回
                if(antPathMatcher.match(menu.getUrl(),requestUrl)){
                    String[] str = menu.getRoles().stream().map(Role::getName).toArray(String[]::new);
                    return SecurityConfig.createList(str);
                }
            }
            //没匹配的url默认登录即可访问
            return SecurityConfig.createList("ROLE_LOGIN");
        }

        @Override
        public Collection<ConfigAttribute> getAllConfigAttributes() {
            return null;
        }

        @Override
        public boolean supports(Class<?> aClass) {
            return false;
        }
    }


以上例子:通过请求路径去数据库中查询对应的角色权限,得到角色权限。通过SecurityConfig.createList(str)方法对得到的角色权限进行设置。

其中SecurityConfig是上述ConfigAttribute的子类,其中createList方法对权限的信息进行了设置。然后又通过getAttribute进行获取。

    //createList
    public static List<ConfigAttribute> createList(String... attributeNames) {
        Assert.notNull(attributeNames, "You must supply an array of attribute names");
        List<ConfigAttribute> attributes = new ArrayList(attributeNames.length);
        String[] var2 = attributeNames;
        int var3 = attributeNames.length;

        for(int var4 = 0; var4 < var3; ++var4) {
            String attribute = var2[var4];
            //此处进行了角色权限设置
            attributes.add(new SecurityConfig(attribute.trim()));
        }
        return attributes;
    }
    //getAttribute
    public String getAttribute() {
        return this.attrib;
    }

②自定义角色权限的判断
在FilterSecurityInterceptord中也对角色权限判断的方法进行调用,通过invoke方法调用父类AbstractSecurityInterceptor,然后父类通过调用accessDecisionManager.decide(authenticated, object, attributes)方法作出决定,是否符合权限的信息。

我们可以通过实现实现AccessDecisionManager接口,重写decide方法,自定义其中的权限规则。

@Component
public class CustomUrlDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        for(ConfigAttribute configAttribute:collection){
            //当前url所需要的角色
            String needRole = configAttribute.getAttribute();
            //判断角色是否登录,能否可以访问。此角色在CustomFilter中设置
            if("ROLE_LOGIN".equals(needRole)){
                //判断是否为登录
                if(authentication instanceof AnonymousAuthenticationToken){
                    throw new AccessDeniedException("尚未登录,请登录!");
                }else{
                    return;
                }
            }
            //判断用户角色是否为url所需角色
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for(GrantedAuthority grantedAuthority:authorities){
                if(grantedAuthority.getAuthority().equals(needRole)){
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足,请联系管理员!");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}

最后对我们自定义的SecurityMetadataSource对象和AccessDecisionManager对象进行设置。

对于FilterSecurityInterceptord是自动调用默认规则的,所以我们需要对这个规则进行改变,使用我们的规则。

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        //使用jwt不需要csrf
        http.csrf().disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
//                .antMatchers("/login","/logout")
//                .permitAll()
                //除上面,所有请求都需要认证
                .anyRequest()
                .authenticated()
                //设置自定义规则
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                        o.setAccessDecisionManager(customUrlDecisionManager);
                        o.setSecurityMetadataSource(customFilter);
                        return o;
                    }
                })

    }


最后附上流程图

在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security是一个用于在Java应用程序中实现身份验证和授权的框架。它提供了一种可靠和灵活的方法来管理应用程序中的权限。通过使用Spring Security,可以轻松地自定义登录授权过程。 首先,我们需要创建一个实现`UserDetailsService`接口的类来处理用户的身份验证。在这个类中,我们可以自定义用户的登录逻辑,例如验证用户名和密码。我们可以使用Spring Security提供的各种验证方法来验证用户的身份。 接下来,我们需要配置Spring Security来处理用户的授权。可以使用`WebSecurityConfigurerAdapter`类扩展一个配置类,并覆盖其中的`configure`方法。在这个方法中,我们可以指定哪些URL需要受到保护,哪些URL可以公开访问。例如,我们可以使用`antMatchers`方法来指定URL模式,然后使用`hasAuthority`或`hasRole`方法来指定用户需要具备的权限角色。 另外,我们还可以使用`@PreAuthorize`注解来在方法级别上进行授权。可以在需要进行授权的方法上添加该注解,并指定用户需要具备的权限角色。 最后,我们还可以通过自定义`AuthenticationProvider`来实现更复杂的授权逻辑。可以创建一个实现该接口的类,并在其中实现自定义的身份验证和授权逻辑。然后可以将这个自定义的`AuthenticationProvider`添加到Spring Security的配置中。 通过以上的方法,我们可以灵活地自定义登录授权过程。Spring Security提供了丰富的配置选项和接口来满足各种不同的授权需求。使用Spring Security,我们可以有效地管理应用程序中的权限,并确保只有具备合适权限的用户可以访问受保护的资源。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值