Skip to content

Unauthorized when authenticated user is shown an error page #12070

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
sjohnr opened this issue Oct 19, 2022 · 0 comments
Closed

Unauthorized when authenticated user is shown an error page #12070

sjohnr opened this issue Oct 19, 2022 · 0 comments
Assignees
Labels
in: config An issue in spring-security-config type: bug A general bug
Milestone

Comments

@sjohnr
Copy link
Member

sjohnr commented Oct 19, 2022

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

@sjohnr sjohnr self-assigned this Oct 19, 2022
@sjohnr sjohnr added this to the 6.0.0 milestone Oct 19, 2022
@sjohnr sjohnr added in: config An issue in spring-security-config type: bug A general bug labels Oct 19, 2022
rwinch added a commit to rwinch/spring-security that referenced this issue Oct 20, 2022
Previously the default was an HttpSessionSecurityContextRepository which
meant that if a stateless authentication occurred the SecurityContext would
be lost on ERROR dispatch.

This commit ensures that the RequestAttributeSecurityContextRepository is
also consulted by default.

Closes spring-projectsgh-12070
@rwinch rwinch closed this as completed in 9cb668a Oct 20, 2022
@sjohnr sjohnr assigned rwinch and unassigned sjohnr Oct 20, 2022
@rwinch rwinch modified the milestones: 6.0.0, 6.0.0-RC2 Nov 7, 2022
wilkinsona added a commit to spring-projects/spring-aot-smoke-tests that referenced this issue Nov 10, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
in: config An issue in spring-security-config type: bug A general bug
Projects
None yet
Development

No branches or pull requests

2 participants