如何解决通过角色保护特定端点
我正在尝试使用受Spring Security保护的Spring Boot构建REST API。在这里,我需要提供/ users终结点,该终结点仅对具有ADMIN角色的用户可用。
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
SecurityContext context = SecurityContextHolder.createEmptyContext();
Authentication authentication =
new TestingAuthenticationToken("username","password","ROLE_ADMIN");
context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);
http.authorizeRequests()
.antMatchers("/users").hasRole("ADMIN")
.antMatchers("/products").permitAll()
;
}
}
我正在将TestingAuthenticationToken与ROLE_ADMIN一起使用,因此我希望/ users端点在此配置中可用。
请求
GET /users HTTP/1.1
Host: localhost:5000
Accept: application/json
Content-Type: application/json
Cache-Control: no-cache
响应:
"timestamp": "2020-09-01T17:28:27.628+00:00","status": 403,"error": "Forbidden","message": "Access Denied","path": "/users"
}
解决方法
在SecurityContext
中的每个请求期间,都会检索Authentication
及其SecurityContextPersistenceFilter
。因此,SecurityContext
中的SecurityConfig
会被简单地覆盖(用auth == null
覆盖)。没有身份验证意味着没有角色,因此禁止403-
有关更多信息,请参见here。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。