What is username and password when starting Spring Boot with Tomcat?
Asked Answered
O

11

197

When I deploy my Spring application via Spring Boot and access localhost:8080 I have to authenticate, but what is the username and password or how can I set it? I tried to add this to my tomcat-users file but it didn't work:

<role rolename="manager-gui"/>
    <user username="admin" password="admin" roles="manager-gui"/>

This is the starting point of the application:

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }
}

And this is the Tomcat dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>

How do I authenticate on localhost:8080?

Onions answered 17/5, 2016 at 19:46 Comment(3)
By setting up spring-boot-starter-security.Rat
You need to authenticate = you want to have authentication? Because there is no authentication nor username & password in spring-boot-starter-tomcat/-web. If you see some, it's probably a different application on :8080Goodsized
And it's printed on the console at launch.Insinuation
D
384

I think that you have Spring Security on your class path and then spring security is automatically configured with a default user and generated password

Please look into your pom.xml file for:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

If you have that in your pom than you should have a log console message like this:

Using default security password: ce6c3d39-8f20-4a41-8e01-803166bb99b6

And in the browser prompt you will import the user user and the password printed in the console.

Or if you want to configure spring security you can take a look at Spring Boot secured example

It is explained in the Spring Boot Reference documentation in the Security section, it indicates:

The default AuthenticationManager has a single user (‘user’ username and random password, printed at `INFO` level when the application starts up)

Using default security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35
Defamation answered 18/5, 2016 at 1:36 Comment(11)
If you fine tune your logging configuration, ensure that the org.springframework.boot.autoconfigure.security category is set to log INFO messages, otherwise the default password will not be printed.Toothsome
beautiful. everything defaulted to something. double edged sword.Undrape
for my case (spring boot vs:2.0.4) console is "Using generated security password: eb7a9e02-b9cc-484d-9dec-a295b96d94ee"Fizz
This was just the case for me too. I was just about to start asking question about it.Oleoresin
@Marcel I have added the spring security in class path, and can see the generated password, But when I use in basic auth via postman as username as user and password as generated password. I am getting unauthorised.Bantamweight
I am facing the same issue that @Lokesh Pandey is facing . I am using postman and used the generated password and username as user in basic authentication. but its not working.Tobietobin
@Tobietobin that's because of the spring security. I know why that issue is happening. I will recommend you to go through this incredible article which will give you enough insight on spring security marcobehler.com/guides/spring-securityBantamweight
@LokeshPandey I understand that's because of Spring Security, also the automatically generated password which is being printed on console, I am using the same. Still postman says 401 UnAuthorized. Should I need to have my own username password implementation. I mean what if I do not want to do that, I only need to use the default password that spring generated. Simple as that it should have been, but it doesn't seem to.Tobietobin
@Tobietobin that's the hashed password.Bantamweight
So which means there is no way I could decode this password and use it in postman.Tobietobin
The Spring Boot secured example github project linked above does not exist anymore. It has been moved seemingly to spring-projects/spring-security-samples.Krysta
S
69

If spring-security jars are added in classpath and also if it is spring-boot application all http endpoints will be secured by default security configuration class SecurityAutoConfiguration

This causes a browser pop-up to ask for credentials.

The password changes for each application restarts and can be found in console.

Using default security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35

To add your own layer of application security in front of the defaults,

@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}

or if you just want to change password you could override default with,

application.xml

security.user.password=new_password

or

application.properties

spring.security.user.name=<>
spring.security.user.password=<>
Superincumbent answered 6/10, 2017 at 13:11 Comment(4)
i just added spring.security.user.name=<> spring.security.user.password=<> to the application.properties file. I did not do anything else. Still it worked.Artistry
You have your property name wrong in the xml example It's spring.security.user.password=xxx Not sure about the XML formatting either as we use .yml filesSphalerite
When using the inMemoryAuthentication you rather prefix your password with {noop} when you receive the error: There is no PasswordEncoder mapped for the id “null”Decease
add this in SecurityConfig class @Bean public PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); } It can fix There is no PasswordEncoder mapped for the id “null”Tertius
A
20

When overriding

spring.security.user.name=
spring.security.user.password=

in application.properties, you don't need " around "username", just use username. Another point, instead of storing raw password, encrypt it with bcrypt/scrypt and store it like

spring.security.user.password={bcrypt}encryptedPassword
Androsterone answered 20/7, 2019 at 11:57 Comment(0)
T
5

If you can't find the password based on other answers that point to a default one, the log message wording in recent versions changed to

Using generated security password: <some UUID>
Trashy answered 28/4, 2018 at 18:23 Comment(0)
C
3

You can also ask the user for the credentials and set them dynamically once the server starts (very effective when you need to publish the solution on a customer environment):

@EnableWebSecurity
public class SecurityConfig {

    private static final Logger log = LogManager.getLogger();

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        log.info("Setting in-memory security using the user input...");

        Scanner scanner = new Scanner(System.in);
        String inputUser = null;
        String inputPassword = null;
        System.out.println("\nPlease set the admin credentials for this web application");
        while (true) {
            System.out.print("user: ");
            inputUser = scanner.nextLine();
            System.out.print("password: ");
            inputPassword = scanner.nextLine();
            System.out.print("confirm password: ");
            String inputPasswordConfirm = scanner.nextLine();

            if (inputUser.isEmpty()) {
                System.out.println("Error: user must be set - please try again");
            } else if (inputPassword.isEmpty()) {
                System.out.println("Error: password must be set - please try again");
            } else if (!inputPassword.equals(inputPasswordConfirm)) {
                System.out.println("Error: password and password confirm do not match - please try again");
            } else {
                log.info("Setting the in-memory security using the provided credentials...");
                break;
            }
            System.out.println("");
        }
        scanner.close();

        if (inputUser != null && inputPassword != null) {
             auth.inMemoryAuthentication()
                .withUser(inputUser)
                .password(inputPassword)
                .roles("USER");
        }
    }
}

(May 2018) An update - this will work on spring boot 2.x:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final Logger log = LogManager.getLogger();

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Note: 
        // Use this to enable the tomcat basic authentication (tomcat popup rather than spring login page)
        // Note that the CSRf token is disabled for all requests
        log.info("Disabling CSRF, enabling basic authentication...");
        http
        .authorizeRequests()
            .antMatchers("/**").authenticated() // These urls are allowed by any authenticated user
        .and()
            .httpBasic();
        http.csrf().disable();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        log.info("Setting in-memory security using the user input...");

        String username = null;
        String password = null;

        System.out.println("\nPlease set the admin credentials for this web application (will be required when browsing to the web application)");
        Console console = System.console();

        // Read the credentials from the user console: 
        // Note: 
        // Console supports password masking, but is not supported in IDEs such as eclipse; 
        // thus if in IDE (where console == null) use scanner instead:
        if (console == null) {
            // Use scanner:
            Scanner scanner = new Scanner(System.in);
            while (true) {
                System.out.print("Username: ");
                username = scanner.nextLine();
                System.out.print("Password: ");
                password = scanner.nextLine();
                System.out.print("Confirm Password: ");
                String inputPasswordConfirm = scanner.nextLine();

                if (username.isEmpty()) {
                    System.out.println("Error: user must be set - please try again");
                } else if (password.isEmpty()) {
                    System.out.println("Error: password must be set - please try again");
                } else if (!password.equals(inputPasswordConfirm)) {
                    System.out.println("Error: password and password confirm do not match - please try again");
                } else {
                    log.info("Setting the in-memory security using the provided credentials...");
                    break;
                }
                System.out.println("");
            }
            scanner.close();
        } else {
            // Use Console
            while (true) {
                username = console.readLine("Username: ");
                char[] passwordChars = console.readPassword("Password: ");
                password = String.valueOf(passwordChars);
                char[] passwordConfirmChars = console.readPassword("Confirm Password: ");
                String passwordConfirm = String.valueOf(passwordConfirmChars);

                if (username.isEmpty()) {
                    System.out.println("Error: Username must be set - please try again");
                } else if (password.isEmpty()) {
                    System.out.println("Error: Password must be set - please try again");
                } else if (!password.equals(passwordConfirm)) {
                    System.out.println("Error: Password and Password Confirm do not match - please try again");
                } else {
                    log.info("Setting the in-memory security using the provided credentials...");
                    break;
                }
                System.out.println("");
            }
        }

        // Set the inMemoryAuthentication object with the given credentials:
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        if (username != null && password != null) {
            String encodedPassword = passwordEncoder().encode(password);
            manager.createUser(User.withUsername(username).password(encodedPassword).roles("USER").build());
        }
        return manager;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
Conjugated answered 28/11, 2017 at 7:27 Comment(0)
H
2

Addition to accepted answer -

If password not seen in logs, enable "org.springframework.boot.autoconfigure.security" logs.

If you fine-tune your logging configuration, ensure that the org.springframework.boot.autoconfigure.security category is set to log INFO messages, otherwise the default password will not be printed.

https://docs.spring.io/spring-boot/docs/1.4.0.RELEASE/reference/htmlsingle/#boot-features-security

Holdover answered 5/4, 2019 at 6:6 Comment(0)
E
1

Ref- Spring Boot 3 + Spring Security 6 Default username password generation in depth
When we start the spring boot application which has spring security dependency as follows-

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

Then UserDetailsServiceAutoConfiguration creates a custom Spring Security User class with default username user and generated password. This Spring Security User class is then provided to InMemoryUserDetailsManager. enter image description here If the user creates its own UserDetailsService bean, then the UserDetailsServiceAutoConfiguration gets automatically disabled. In this case we pass the new created user to be used by the InMemoryUserDetailsManager.
With the new Spring Boot 3 + Spring Security 6 configuration the code snippet for this is

@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.formLogin();
        http.authorizeHttpRequests().anyRequest().authenticated();
        return http.build();
    }
    
    @Bean
    UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager userDetailsService = new InMemoryUserDetailsManager();
        UserDetails user = User.withUsername("javainuse").password("javainuse").authorities("read").build();
        userDetailsService.createUser(user);
        return userDetailsService;
    }

}
Etiquette answered 22/8, 2023 at 15:11 Comment(0)
B
0

As of Spring Security version 5.7.1, the default username is user and the password is randomly generated and displayed in the console (e.g. 8e557245-73e2-4286-969a-ff57fe326336).

Please see the documentation for further details:

https://docs.spring.io/spring-security/reference/servlet/getting-started.html

Boykins answered 21/5, 2022 at 4:12 Comment(0)
H
-1

When I started learning Spring Security, then I overrided the method userDetailsService() as in below code snippet:

@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfiguration extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/", "/index").permitAll()
                .anyRequest().authenticated()
                .and()
                .httpBasic();
    }

    @Override
    @Bean
    public UserDetailsService userDetailsService() {
        List<UserDetails> users= new ArrayList<UserDetails>();
        users.add(User.withDefaultPasswordEncoder().username("admin").password("nimda").roles("USER","ADMIN").build());
        users.add(User.withDefaultPasswordEncoder().username("Spring").password("Security").roles("USER").build());
        return new InMemoryUserDetailsManager(users);
    }
}

So we can log in to the application using the above-mentioned creds. (e.g. admin/nimda)

Note: This we should not use in production.

Hemicrania answered 26/12, 2019 at 16:14 Comment(0)
N
-1

Try to take username and password from below code snipet in your project and login and hope this will work.

@Override
    @Bean
    public UserDetailsService userDetailsService() {
        List<UserDetails> users= new ArrayList<UserDetails>();
        users.add(User.withDefaultPasswordEncoder().username("admin").password("admin").roles("USER","ADMIN").build());
        users.add(User.withDefaultPasswordEncoder().username("spring").password("spring").roles("USER").build());
        return new UserDetailsManager(users);
    }
Nicknack answered 17/3, 2020 at 13:45 Comment(0)
S
-1

For a start simply add the following to your application.properties file

spring.security.user.name=user
spring.security.user.password=pass

NB: with no double quote

Run your application and enter the credentials (user, pass)

Sordino answered 9/1, 2021 at 12:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.