There are three ways in which users can be defined in Spring boot security.

One is a default user created by Spring and other two are used to change default username and password.
Both of these disable default user name and password creation by Spring security.

All the three methods are discussed in this article.

Method 1: Spring boot security auto configuration
As a part of Spring boot security auto configuration, if you do nothing, then Spring boot creates a user with name user and generates a password at application startup.
This password is visible on application console and changes every time it restarts as shown below,

2020-04-24 22:23:51.358 INFO 14272 — [ main] .s.s.UserDetailsServiceAutoConfiguration :

Using generated security password: 956f97e5-8e7a-4821-ae38-e59354456567

2020-04-24 22:23:53.538 INFO 14272 — [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain

Method 2: Using file
If you do not want to go with the default username and password generated by Spring boot security(or override it) or simply disable it, define following properties in file.

Defining a username and password here will disable automatic generation of a user and you will not see the password written on the console.
If there is no file, create it in the root directory or src/main/resources folder.

Method 3: In memory user creation
If is not your choice, Spring boot security provides another way to change default user and password, inside application code or in-memory.
For this, you need to tweak into Spring’s default behavior and provide a class that overrides this behavior.
This class must extend WebSecurityConfigurerAdapter and override its configure method as shown below.



public class SecurityConfig extends WebSecurityConfigurerAdapter {

   protected void configure(AuthenticationManagerBuilder builder) throws Exception {

With this method, you can create multiple users at once using and() method.
Note that you also need to provide roles of created users otherwise an error will be thrown.

java.lang.IllegalArgumentException: Cannot pass a null GrantedAuthority collection

A role need not be “USER” or “ADMIN”, it can be any String which could be later used to provide or restrict access to certain URLs and resources.

Be careful to override configure that takes an argument of type AuthenticationManagerBuilder since there is another overridable configure method that takes an object of type HttpSecurity as argument.

In case, you have created users in both and in-memory users, any of those can be used for login.
Hope this article was useful, do not go away without hitting that clap.


Leave a Reply