Spring Security - In-Memory Authentication
Configure inMemory Authentication
In Memory Authentication Code Example
Here is an example to set In Memory Authentication. There are two users created. The first user is user and the second user is admin.
user has role “ROLE_USER” only and admin has roles “USER” and “ROLEADMIN”.
SecurityConfiguration.java
1 | import org.springframework.context.annotation.Bean; |
Here we use the default password encoder. You get the default password encoder by calling PasswordEncoderFactories.createDelegatingPasswordEncoder();
. The default password encoder uses Bcrypt to encode password.
For Spring Security we don’t usually directly create AuthenticaitonProvider to handle authentication request. instead, we use AuthenticationManagerBuilder to configure authentication.
roles()
method automatically prefixes each entry with “ROLE_”. So just pass “USER” or “ADMIN” as parameter.
AuthenticationManagerBuilder
- AuthenticationManagerBuilder is a SecurityBuilder used to create an AuthenticationManager. Allows for easily building in memory authentication, LDAP authentication, JDBC based authentication, adding UserDetailsService, and adding AuthenticationProvider’s.
- It has a
List<AuthenticationProvider>
andUserDetailsService
field that is used for authenticate users. - inMemoryAuthentication(), jdbcAuthentication(), ldapAuthentication() method can be used to configure AuthenticationProvider and UserdetailsService
- userDetailsService(T userDetailsService) method can be used to configure a custom UserDetailsService
In Memory Authentication
AuthenticationManagerBuilder.inMemoryAuthentication() method adds in memory authentication to the AuthenticationManagerBuilder and return a InMemoryUserDetailsManagerConfigurer to allow customization of the in memory authentication. InMemoryUserDetailsManagerConfigurer itself uses DaoAuthenticaionProvider as the provider. InMemoryUserDetailsManagerConfigurer.withUser() method adds a user to the UserDetailsService.
Reference