【问题标题】:Secure specific endpoint by role按角色保护特定端点
【发布时间】: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


    【解决方案1】:

    SecurityContext 及其Authentication 在SecurityContextPersistenceFilter 中的每个请求期间被检索。因此,您在SecurityConfig 中的SecurityContext 会被简单地覆盖(使用auth == null)。没有身份验证意味着没有角色,因此 403 - 禁止。

    更多信息请见here。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多