I want to add simple config for basic authentication using spring security InMemoryUserDetailsManager
After adding following configuration I am able to authenticate with the in memory user (myUser) and the password for this user:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(inMemoryUserDetailsManager());
}
@Bean
public InMemoryUserDetailsManager inMemoryUserDetailsManager() {
List<UserDetails> userDetailsList = new ArrayList<>();
userDetailsList.add(User.withUsername("myUser").password(passwordEncoder().encode("password"))
.roles("USER").build());
return new InMemoryUserDetailsManager(userDetailsList);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
The thing is that if I change the password from postman I am still able to authenticate. If I stop application server and start the application again and try with wrong password and correct username it returns 401 ( which is expected). However if next request is sent with the correct header with username and password (myUser, password) and then send the request after that with wrong password it seems the wrong password is accepted. As soon as I change the username to some random word it returns 401 unauthorized. Something is missing from my configuration and I do not have a clue what is it.
CodePudding user response:
Spring by default stores the HttpSession of the Authentication details. So whenever user logs in and authentication is successful, the details are stores in ThreadLocal and whenever the next login happens, it picks it up from the security context instead of authenticating again. Spring Security provides multiple Policies for Session Management. For your use case, you need to configure your HttpSecurity with SessionCreationPolicy.STATELESS.
http
.csrf()
.disable()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
You can also refer the below article for detailed information: https://www.javadevjournal.com/spring-security/spring-security-session/