【发布时间】:2021-09-21 23:44:20
【问题描述】:
我正在开发启用授权和资源服务器的 Spring Boot 和 Spring Security Web 应用程序。我已经定义了一组分配了角色的用户,并尝试实现对 REST 端点的基于角色的访问。我能够实现对端点的基于令牌的访问,但不能限制对最终用户的访问,这将基于他们的角色。
我已经完成了两个端点:/rest/products/list 和 /rest/products/add,并尝试使用 ADMIN 角色的用户限制对 /rest/products/add 端点的访问。
我的WebSecurityConfigurerAdapter如下:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private PasswordEncoder passwordEncoder;
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.passwordEncoder(passwordEncoder)
.withUser("user1")
.password(passwordEncoder.encode("user1Pass"))
.roles("USER")
.and()
.withUser("user2")
.password(passwordEncoder.encode("user2Pass"))
.roles("USER")
.and()
.withUser("admin")
.password(passwordEncoder.encode("adminPass"))
.roles("ADMIN");
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/rest/products/add").hasAnyRole("ADMIN")
.antMatchers("/rest/products/list").denyAll();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
因此,admin / adminPass 用户只能访问资源 /rest/products/add,前提是该用户具有 ADMIN 角色。但是如果尝试使用 user1 / user1Pass,它仍然可以访问:
获取 user1 邮递员屏幕的访问令牌
仅使用user1 Postman 屏幕访问ADMIN 相关端点
此外,我在配置方法中添加了(出于测试目的)以下规则.antMatchers("/products/list").denyAll(); Here 表示任何用户都不应访问/products/list。但它仍然继续响应(提供访问正确的令牌)。
在这里How to fix role in Spring Security? 的类似问题中,匹配器的顺序应该是从更具体到更少。但在我的例子中,有两个匹配器并且没有匹配器可以重叠它们。
我正在使用带有 spring-boot-starter-security 插件版本 2.5.2 的 Spring Boot。
应该进行哪些额外配置才能使.hasRole("ADMIN") 和.denyAll() 按预期工作?
【问题讨论】:
标签: spring-boot spring-security spring-security-oauth2