Describe the bug
@SpringBootTest integration tests that check the implementation of the authentication setup fail if the SessionCreationPolicy is NEVER or STATELESS. The application works as intended but when executing the test, the authenticated() method cannot verify this.
To Reproduce
1. Configure Spring Security to NEVER create sessions or be STATELESS
2. Write a @SpringBootTest that makes a request and expect to be authenticated .andExpect(authenticated())
3. Observe that the test fails with this stack trace
4. Verify with an HTTP client of your choice that, when the application is started normally, the user is authenticated
Relevant Code Snippets:
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
@Test
void withHeader() throws Exception {
mvc.perform(get("/")
.header("Authorization", "Basic dXNlcjpwYXNzd29yZA=="))
.andExpect(authenticated());
}
Expected behaviour The test should pass. Disabling sessions should not cause the tests to fail. Furthermore, there should be no discrepancy between the running application and its behaviour in an integration test.
Sample For your convenience, I have uploaded a minimal, reproducible sample to GitHub.
Debugging
From my limited understanding, I think that the test fails because not allowing sessions will initialize a NullSecurityContextRepository which does not hold any credentials. However, I am not too sure whether this is correct and makes any sense.
This is my first report here. Please let me know if it needs any adjustment! :)
Comment From: rwinch
Thanks for the detailed report and the sample. This is expected behavior. Once the request completes, the user is no longer authenticated. In a stateless scenario, your best to verify that you get an appropriate HTTP status code back to determine if authentication was successful.
Comment From: levinwinter
I see! Thank you very much for having a look into this :)