Describe the bug When someone tries to access public API with invalid access token in HttpOnly cookie format or in Authorization header then 401 error is received.

  • Note it is recommended to use HttpOnly cookie to store tokens at client side and at client end httpOnly cookies cannot be read or modified, therefore it is not possible to selectively not send access token to public APIs. HttpOnly Cookie usage: https://medium.com/@nurettinabaci/csrf-token-and-httponly-ff19fcc24862

  • This seems a miss from spring security end and it should be handled at springboot end only.

To Reproduce Steps to reproduce the behavior.

@Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                .authorizeHttpRequests(authorize ->
                        authorize
                                .requestMatchers(HttpMethod.GET, "/sample").permitAll()  
 .anyRequest().authenticated()
                )
    }
  • Note it is trimmed code, in resolver I am fetching access token from httpOnly cookie.

Expected behavior - Should receive 200 response on requesting public API with invalid access token or random string in httpOnly Cookie or in Authorization header.

Sample This issue is same as raised by someone previously here: https://github.com/spring-projects/spring-security/issues/12599

Comment From: jzheaux

Thanks for reaching out, @SahilSeewal1.

This is by design. Generally speaking, an authorization system would need to know who the user is before knowing whether the user can do X, Y, or Z operation. And even with a public endpoint, the endpoint may behave differently when a user is in context. So, in the end, they are separate systems with authentication coming first: If a request presents credentials, the framework will try to authenticate the user and accept or deny the request accordingly.

That said, I understand your point. If you know that these endpoints never care who the user is, then please consider listing your permit-all endpoints in a separate filter chain that does not declare an authentication mechanism like so:

@Order(0)
public SecurityFilterChain publicEndpoints(HttpSecurity http) throws Exception {
    http
        .securityMatchers("/my", "/public", "/endpoints")
        .authorizeHttpRequests((authorize) -> authorize.anyRequest().permitAll())
    return http.build();
}

@Order(1)
// ... your other endpoints

I've added https://github.com/spring-projects/spring-security/issues/14122 to update the documentation.