SpringSecurity的PermitAll、WebSecurityCustomizer和授权

在SpringSecurity的日常开发中,可能使用SpringSecurity的PermitAll()请求还是会被拦截,这是为什么呢?

public WebSecurityCustomizer webSecurityCustomizer(){
        return web->{
            web.ignoring().antMatchers("/login","/logout","/captcha");
        };
    }

        httpSecurity.authorizeRequests()
                .antMatchers("/login","/logout","/captcha").permitAll()
                .anyRequest().authenticated()

当使用WebSecurityCustomizer的时候,过滤器会忽略后面请求的路径,默认就不会走springSecurity的过滤器和重写的springSecurity的过滤器。但是还是会被自定义的过滤器所拦截。因此常用于静态页面等的存放。

当使用PermitAll的时候,SpringSecurity会拿到你放行的请求进行判断,因此不会被SpringSecurity默认的过滤器所拦截,但是可能会被我们重写的过滤器所拦截,但是当在授权的时候如果实现了FilterInvocationSecurityMetadataSource(授权时的元数据,如果基于RBAC框架,就是当前请求所需要的角色进行判断),也需要判断是否是放行的资源,然后在重写的

AccessDecisionManager决定是否放行,根据不同的角色判断出不同的情况。

判断当前的请求需要哪些角色,如果与UrlConstant中需要放行的请求相对应,就返回null,然后在

AccessDecisionManager中进行相应的判断

@Component
public class CustomerFilter implements FilterInvocationSecurityMetadataSource {
    @Autowired
    private IMenuService menuService;
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        //获取到登录请求的url
        String url = ((FilterInvocation) object).getRequestUrl();
        for (String s : UrlConstant.urls) {
            if(antPathMatcher.match(s,url)){
                return null;
            }
        }
        List<Menu> menuList = menuService.getMenuWithRole();
        for (Menu menu : menuList) {
            if (antPathMatcher.match(menu.getUrl(), url)) {
                String[] strings = menu.getRoles().stream().map(it -> {
                    return it.getName();
                }).toArray(String[]::new);
                //转换为
                return SecurityConfig.createList(strings);
            }
        }
        return SecurityConfig.createList("ROLE_LOGIN");
    }

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

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}

 决定此次请求是否被允许访问的

@Component
public class CustomerDecisionFilter implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        if(configAttributes.isEmpty()||configAttributes.size()==0){
            return;
        }
        for (ConfigAttribute configAttribute : configAttributes) {
            //这就是当前url需要的角色,满足其中一个角色就可以了
            String attribute = configAttribute.getAttribute();
            if("ROLE_LOGIN".equals(attribute)){
                //判断当前是否登录,如果没有登录
                return;
            }
            //取出当前的角色
            //TODO
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                String authorityAuth = authority.getAuthority();
                if(authorityAuth.equals(attribute)){
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足");
    }

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

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Spring Security是一个开源的安全框架,提供了基于权限的访问控制、身份认证、安全性事件发布等功能。在Spring Boot应用中使用Spring Security可以非常方便地实现用户身份认证和授权Spring Security实现身份认证和授权的步骤如下: 1.添加Spring Security依赖,可以在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2.创建一个继承自WebSecurityConfigurerAdapter的配置类,并重写configure方法,配置用户认证和授权信息。例如: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("{noop}password").roles("USER") .and() .withUser("admin").password("{noop}password").roles("USER", "ADMIN"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/**").hasAnyRole("USER", "ADMIN") .and().formLogin(); } } ``` 上述代码中,configureGlobal方法配置了两个用户,一个是user,一个是admin,密码都是password,其中admin用户具有ADMIN角色,user用户具有USER角色。configure方法配置了访问/admin/**路径的请求需要ADMIN角色,访问其他路径的请求需要USER或ADMIN角色,并启用了表单登录。 3.在应用程序的配置文件中配置用户名和密码。例如: ```properties spring.security.user.name=user spring.security.user.password=password ``` 以上就是Spring Security实现身份认证和授权的基本步骤。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值