我已经实现了 UserDetailsService
来为我的 Spring Boot REST 服务返回带有 SimpleGrantedAuthority
的 UserDetails
实例。我有 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/