按角色保护特定终结点



我正在尝试使用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及其AuthenticationSecurityContextPersistenceFilter中的每个请求期间都会被检索。因此,SecurityConfig中的SecurityContext被简单地覆盖(用auth == null(。没有身份验证意味着没有角色,因此403-被禁止。

欲了解更多信息,请参阅此处。

最新更新