Skip to content

Unauthorized when authenticated user is shown an error page #12070

@sjohnr

Description

@sjohnr

Describe the bug
When an error occurs during the request, an authenticated user is shown a 401 Unauthorized instead of a Spring Boot error page.

To Reproduce

See sample below.

> http :8080/500 -a user:password

HTTP/1.1 401 
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Connection: keep-alive
Content-Length: 0
Date: Wed, 19 Oct 2022 21:20:04 GMT
Expires: 0
Keep-Alive: timeout=60
Pragma: no-cache
Set-Cookie: JSESSIONID=BCF137B4BD32F53583BE34C18249D1B0; Path=/; HttpOnly
WWW-Authenticate: Basic realm="Realm"
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 0

Expected behavior
Authenticated users should be shown an error page. The following response is expected:

> http :8080/500 -a user:password

HTTP/1.1 500 
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Connection: close
Content-Type: application/json
Date: Wed, 19 Oct 2022 21:22:26 GMT
Expires: 0
Pragma: no-cache
Transfer-Encoding: chunked
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 0

{
    "error": "Internal Server Error",
    "path": "/500",
    "status": 500,
    "timestamp": "2022-10-19T21:22:26.653+00:00"
}

Sample

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

@RestController
public class DemoController {

    @GetMapping("/")
    public Map<String, String> home(@AuthenticationPrincipal User user) {
        return Map.of("message", "You are logged in, " + user.getUsername() + "!");
    }

    @GetMapping("/500")
    public void error() {
        throw new RuntimeException("Bad things happened");
    }

    @GetMapping("/hello")
    public String hello() {
        return "Hello";
    }

}

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .authorizeHttpRequests((authorize) -> authorize
                .requestMatchers("/hello").permitAll()
                .anyRequest().authenticated()
            )
            // TODO: Uncomment the following to work around the bug.
//            .securityContext((securityContext) -> securityContext
//                .securityContextRepository(new DelegatingSecurityContextRepository(
//                    new RequestAttributeSecurityContextRepository(),
//                    new HttpSessionSecurityContextRepository()
//                ))
//            )
            .httpBasic(Customizer.withDefaults())
            .formLogin(Customizer.withDefaults());
        // @formatter:on

        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        // @formatter:off
        UserDetails userDetails = User.withDefaultPasswordEncoder()
            .username("user")
            .password("password")
            .roles("USER")
            .build();
        // @formatter:on

        return new InMemoryUserDetailsManager(userDetails);
    }

}

Related gh-12023

Metadata

Metadata

Assignees

Labels

in: configAn issue in spring-security-configtype: bugA general bug

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions