java - WebSecurityConfigurerAdapter 配置重叠权限

标签 java spring-boot spring-security spring-rest

我已经实现了 UserDetailsS​​ervice 来为我的 Spring Boot REST 服务返回带有 SimpleGrantedAuthorityUserDetails 实例。我有 3 个价格页面,其中两个授予对特定端点的访问权限,第三个授予对所有端点的访问权限。

我已按如下方式配置我的 WebSecurityConfig。这两个特定权限有效 - 只有它们可以用于访问这些端点。然而,应授予客户端访问所有端点的第三个权限会返回 403 禁止。

protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
        .httpBasic().and()
        .authorizeRequests().antMatchers(“/**/foo/**”).hasAuthority(“foo”).and()
        .authorizeRequests().antMatchers(“/**/moo/**”).hasAuthority(“moo”).and()
        .authorizeRequests().antMatchers(“/**/**”).hasAuthority(“admin”)
}

我尝试过重新排序定义,也尝试过 anyRequest 但它们不起作用。

最佳答案

HttpSecurity#authorizeRequests() javadoc 说:

Note that the matchers are considered in order. Therefore, the following is invalid because the first matcher matches every request and will never get to the second mapping:

http.authorizeRequests().antMatchers("/**").hasRole("USER").antMatchers("/admin/**")
                .hasRole("ADMIN")
<小时/>

也许你想要:

protected void configure(final HttpSecurity http) throws Exception {
    http.csrf().disable()
        .httpBasic().and()
        .authorizeRequests().antMatchers("/**/foo/**").hasAnyAuthority("admin", "foo").and()
        .authorizeRequests().antMatchers("/**/moo/**").hasAnyAuthority("admin", "moo").and()
        .authorizeRequests().antMatchers("/**").hasAuthority("admin");
}

或者,设置RoleHierarchy :

protected void configure(final HttpSecurity http) throws Exception {
    http.csrf().disable()
        .httpBasic().and()
        .authorizeRequests().antMatchers("/**/foo/**").hasAuthority("foo").and()
        .authorizeRequests().antMatchers("/**/moo/**").hasAuthority("moo").and()
        .authorizeRequests().antMatchers("/**").hasAuthority("admin");
}

@Bean
RoleHierarchyVoter roleVoter(final RoleHierarchy roleHierarchy) {
    return new RoleHierarchyVoter(roleHierarchy);
}

@Bean
public RoleHierarchy roleHierarchy() {
    final Map<String, List<String>> hierarchyMap = new HashMap<>();
    hierarchyMap.put("admin", List.of("foo", "moo"));
    final String roleHierarchy = RoleHierarchyUtils.roleHierarchyFromMap(hierarchyMap);

    final RoleHierarchyImpl ret = new RoleHierarchyImpl();
    ret.setHierarchy(roleHierarchy);
    return ret;
}

关于java - WebSecurityConfigurerAdapter 配置重叠权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62300912/

相关文章:

java - SpringBoot,手动控制两个数据源,事务失败

mongodb - 使用 2 个数据库时的 Javers ENTITY_INSTANCE_WITH_NULL_ID

Spring Boot 2、Spring Security 5 和 @WithMockUser

java - 在 java 中骑乘和使用 equals 方法时遇到问题

java - 将 Office 文档转换为 HTML,以便使用 JavaScript 在浏览器中查看

java - Java中如何检查进程是否有错误?

java - Jersey 和 Springboot 应用程序抛出 java.lang.StackOverflowError

spring - 如果用户之前已授权访问,如何绕过 Spring security OAuth2 中的访问确认步骤?

java - Spring-security 甚至在提交表单之前就显示 'Bad Credentials'

java - Spring/Hibernate 响应中的属性为空