我正在尝试使用Spring Boot构建REST API,该API由Spring Security保护。在这里,我需要提供/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
中的每个请求期间都会被检索。因此,SecurityConfig
中的SecurityContext
被简单地覆盖(用auth == null
(。没有身份验证意味着没有角色,因此403-被禁止。
欲了解更多信息,请参阅此处。