Spring Boot
Security
Password
Configuration
Application Development

Remove Using default security password on Spring Boot

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

When developing Spring Boot applications, security is a paramount concern. By default, Spring Boot provides a way to get your application up and running quickly, including a default security configuration. This convenience feature comes with an automatically generated password that is intended to be used temporarily during initial development. However, relying on this default password for production or extended periods poses significant security risks. This article provides detailed guidance on how to disable this default security password and configure your custom security setup in a Spring Boot application.

Why Remove the Default Security Password?

The default security password in Spring Boot is generated and logged to the console at application startup. While this can be convenient during early stages of development, it poses several risks:

  • Security Vulnerabilities: An auto-generated password could be discovered if logs are exposed, leading to unauthorized access.
  • Lack of Customization: Using the default settings restricts the ability to implement custom security requirements or authentication mechanisms.
  • Confusion: It may lead developers to mistakenly assume their application is secure without implementing additional security measures.

Disabling the Default Security Password

Spring Boot's default security configuration can be removed, allowing for custom settings more suited to specific application requirements. Here's how you can do it:

1. Remove the Default Security Configuration

The default password is generated due to Spring Boot's auto-configuration mechanism. To disable this, you can exclude the auto-configured security setup by updating your application.properties or application.yml file:

Using application.properties:

properties
spring.main.allow-bean-definition-overriding=true
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration

Using application.yml:

yaml
1spring:
2  main:
3    allow-bean-definition-overriding: true
4  autoconfigure:
5    exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration

Excluding the SecurityAutoConfiguration disables the default password functionality, allowing you to define a custom security configuration.

2. Implement Custom Security Configuration

With the default configuration excluded, you need to provide your security setup. This is typically done by creating a class annotated with @EnableWebSecurity and extending WebSecurityConfigurerAdapter:

java
1import org.springframework.context.annotation.Configuration;
2import org.springframework.security.config.annotation.web.builders.HttpSecurity;
3import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
4import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
5
6@Configuration
7@EnableWebSecurity
8public class SecurityConfig extends WebSecurityConfigurerAdapter {
9
10    @Override
11    protected void configure(HttpSecurity http) throws Exception {
12        http
13            .csrf().disable() // Enable or disable CSRF as per your need
14            .authorizeRequests()
15            .antMatchers("/public/**").permitAll() // Public endpoints
16            .anyRequest().authenticated()
17            .and()
18            .formLogin()
19            .and()
20            .httpBasic(); // or configure login endpoints
21    }
22}

3. Define Custom Authentication

For more robust security, configure a custom UserDetailsService and authentication provider, such as a database or an LDAP server:

java
1import org.springframework.beans.factory.annotation.Autowired;
2import org.springframework.context.annotation.Bean;
3import org.springframework.context.annotation.Configuration;
4import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
5import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
6import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
7import org.springframework.security.crypto.password.PasswordEncoder;
8import org.springframework.security.provisioning.InMemoryUserDetailsManager;
9import org.springframework.security.core.userdetails.User;
10import org.springframework.security.core.userdetails.UserDetails;
11
12@Configuration
13@EnableWebSecurity
14public class SecurityConfig extends WebSecurityConfigurerAdapter {
15
16    @Override
17    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
18        PasswordEncoder encoder = new BCryptPasswordEncoder();
19        UserDetails user = User.withUsername("user")
20                               .password(encoder.encode("password"))
21                               .roles("USER")
22                               .build();
23
24        auth.userDetailsService(inMemoryUserDetailsManager())
25            .passwordEncoder(encoder);
26    }
27
28    @Bean
29    public InMemoryUserDetailsManager inMemoryUserDetailsManager() {
30        return new InMemoryUserDetailsManager();
31    }
32
33    @Bean
34    public PasswordEncoder passwordEncoder() {
35        return new BCryptPasswordEncoder();
36    }
37}

4. Consider OAuth2 or JWT for Stateless Authentication

For a more modern and scalable solution, consider using OAuth2 for authentication or JSON Web Tokens (JWT) for stateless and token-based authentication mechanisms.

Summary Table

Key StepsDescription
Default Password RiskSecurity vulnerability due to exposed logs
Remove Default ConfigurationExclude SecurityAutoConfiguration using application.*
Custom Security ConfigImplement WebSecurityConfigurerAdapter for flexible auth
User Details ServiceCreate custom user service for authentication
Enhanced AuthenticationConsider OAuth2 or JWT for advanced security needs

Conclusion

Removing the default security password from a Spring Boot application is a vital step in ensuring a secure and robust application. By implementing custom security configurations and authentication mechanisms, developers can tailor the security to fit the unique requirements of their applications. Always be proactive in adopting industry-standard practices when it comes to application security. Implementing robust solutions like OAuth2 or JWT can significantly boost your application's security profile.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.