【发布时间】:2020-12-20 20:50:48
【问题描述】:
我正在尝试使用由 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"
}
【问题讨论】:
标签: spring-boot spring-security