【问题标题】:Spring Security Returns with 403 when there is no Bearer token没有 Bearer 令牌时,Spring Security 返回 403
【发布时间】:2022-12-07 10:53:40
【问题描述】:

我还找不到解决问题的合适方法。我正在使用 Spring Security Oauth2 资源服务器来验证我的请求。这很好用。但是当用不同的场景进行测试时,发现如果没有授权标头存在,或者如果存在授权标头但值不是以承载.

Spring Boot Starter - 2.6.7
Spring Boot Starter Security - 2.6.7
Spring Security Config & Web - 5.6.3
Spring Security Core - 5.3.19
Spring Boot Starter OAuth2 Resource Server - 2.6.7
Spring OAuth2 Resource Server - 5.6.3

我指的是this answer并添加了以下代码BearerTokenAuthenticationEntryPoint.不同之处在于我使用的是内省 url 而不是 jwt。但这无济于事,那部分没有被执行。如果 Bearer 令牌存在,则只执行它。

我在这里错过了什么?

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class CustomResourceServerSecurityConfiguration {

    @Value("${spring.security.oauth2.resourceserver.opaque-token.introspection-uri}")
    String introspectionUri;

    @Value("${spring.security.oauth2.resourceserver.opaque-token.client-id}")
    String clientId;

    @Value("${spring.security.oauth2.resourceserver.opaque-token.client-secret}")
    String clientSecret;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

        http.authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated())
                .oauth2ResourceServer(oauth2 -> oauth2
                        .opaqueToken(opaque -> opaque.introspectionUri(this.introspectionUri)
                                .introspectionClientCredentials(this.clientId, this.clientSecret))
                        .authenticationEntryPoint((request, response, exception) -> {
                            System.out.println("Authentication failed");
                            BearerTokenAuthenticationEntryPoint delegate = new BearerTokenAuthenticationEntryPoint();
                            delegate.commence(request, response, exception);
                        }))

                .exceptionHandling(
                        (exceptions) -> exceptions.authenticationEntryPoint((request, response, exception) -> {
                            System.out.println("Authentication is required");
                            BearerTokenAuthenticationEntryPoint delegate = new BearerTokenAuthenticationEntryPoint();
                            delegate.commence(request, response, exception);
                        }));
        return http.build();
    }
}

【问题讨论】:

    标签: java spring-security spring-security-oauth2 spring-oauth2


    【解决方案1】:

    如果您的情况是,如果 Bearer 令牌丢失,则 POST 获得 403,GET 获得 401,则与 csrf 相关。

    44.2.14 我在执行 POST 时收到 403 Forbidden

    如果 HTTP POST 返回 HTTP 403 Forbidden,但对 HTTP GET 有效,则问题很可能与 CSRF 有关。提供 CSRF 令牌或禁用 CSRF 保护(不推荐)。

    Here's source

    如果您使用 JWT 令牌,那么如果没有任何其他要求,那么您可以禁用它。

      @Bean
        public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
              http.authorizeHttpRequests(authorize -> authorize
                            .anyRequest().authenticated())
                            .csrf().disable()           
                     return http.build();
        } 
    

    4.无状态Spring API

    如果我们的无状态 API 使用基于令牌的身份验证,例如 JWT,我们不需要 CSRF 保护,我们必须像前面看到的那样禁用它

    Source

    【讨论】:

    • JWT 或不透明并不重要。在禁用 CSRF 保护之前你应该确保会话也被禁用(无状态会话管理)
    • 是的,这成功了。而且我还向无状态添加了会话策略。 http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf().disable()
    【解决方案2】:

    使用默认的 conf,当授权标头丢失或无效(格式错误、过期、错误的颁发者......)时,你应该有一个 302(重定向到登录)。如果您有 403,那么您将面临另一个异常(CSRF、CORS 或其他)。设置logging.level.org.sprngframework.security=DEBUG并仔细检查日志

    要更改此默认行为(401 而不是 302),请像在 those tutorials 中那样做:

            http.exceptionHandling().authenticationEntryPoint((request, response, authException) -> {
                response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm="Restricted Content"");
                response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
            });
    

    在样本中,例如 the one for servlets and token introspection,它满足您的确切用例,您甚至可以找到断言 http 状态符合您期望的单元测试:未授权时为 401,拒绝时为 403:

        @Test
    // security-context not set for this test => anonymous
        void greetWitoutAuthentication() throws Exception {
            api.get("/greet").andExpect(status().isUnauthorized());
        }
    
        @Test
    @WithMockBearerTokenAuthentication(authorities = "ROLE_AUTHORIZED_PERSONNEL", attributes = @OpenIdClaims(sub = "Ch4mpy"))
        void securedRouteWithAuthorizedPersonnelIsOk() throws Exception {
            api.get("/secured-route").andExpect(status().isOk());
        }
    
        @Test
    @WithMockBearerTokenAuthentication(authorities = "NOT_A_REQUIRED_ROLE")
        void securedMethodWithoutAuthorizedPersonnelIsForbidden() throws Exception {
            api.get("/secured-method").andExpect(status().isForbidden());
        }
    

    当然,那些测试通过了......

    【讨论】:

    • 你好。仍然不起作用。根据我的理解,不记名令牌也设置了这个标头。
    • 不,它没有。实际上,它默认设置 302(重定向到登录)而不是 403(禁止)。您可能正在处理一个映射到 403 的异常。在您可以在我的答案中应用 conf 之前修复它。
    • 我将 403 用于异常处理程序类 @RestControllerAdvice 中的异常。但这不在安全配置中,它是根据其他一些值动态设置异常的响应状态。没有任何注释。这可能是造成这种情况的原因吗?
    【解决方案3】:

    我有同样的问题,我只是不明白为什么安全团队在请求标头中没有令牌时在默认 AuthenticationEntryPoint 中返回 403。

    我的解决方案是自定义 AuthenticationEntryPoint:

    public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
        private static final Log logger = LogFactory.getLog(CustomAuthenticationEntryPoint.class);
    
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
            logger.debug("Pre-authenticated entry point called. Rejecting access");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access Denied");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-10
      • 2018-08-15
      • 1970-01-01
      • 2015-10-23
      • 2018-08-28
      • 2019-11-08
      • 2020-08-04
      • 2015-03-30
      • 1970-01-01
      相关资源
      最近更新 更多