Experts,,
I have a spring boot 2.5.5 application(embedded tomcat) where I have to configure the basic auth.
This is the class I have that does the work for me
@Component
@EnableWebSecurity
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
}
The issue is I just need to enter the user/password once in the browser and it works for any subsequent request. Furthermore, I don't need to supply the new username/password after the server restarts which is driving me crazy - the app still works and I can access my APIs/pages.
Even if i assume the browser is somehow saving the username and password it should not work once the server is restarted as the password gets changed - isnt it ?
Update II:
Following the advice from M. Deinum I made the session stateless and it worked. I then went on to implement Basic Auth with InMemoryUserDetailsManager and added the below code and we are back to the same issue again. The credentials seem to be again stored in session and I need not pass them for the subsequent request.
@Autowired
public ApplicationSecurityConfig(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
@Override
@Bean
protected UserDetailsService userDetailsService() {
UserDetails user = User
.builder()
.username("admin")
.password(passwordEncoder.encode("admin"))
.roles("ADMINISTRATOR")
.build();
return new InMemoryUserDetailsManager(user);
}
CodePudding user response:
This is how I would expect it to work with your current configuration.
When successfully authenticated with basic authentication the browser will send the username/password for all other subsequent requests. So this is as expected.
Another thing is that, by default, Spring Security will use the HTTP Session to store the user information. A session-cookie is also sent with each request so that the session state can be restored for each request.
This session state is, by default for your servlet container, saved to disc when you stop the server, when you restart and the session is still valid (not timed out) it will still have the authentication.
You can fix this by making Spring Security not use a session (set the session mode to stateless).
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
The drawback of this is that it will re-authenticate each request (which takes some time and thus impacts your performance slightly). But it should give an error after restart now, as you changed the password.