Spring Framework Tutorial

Software Setup and Configuration (STS/Eclipse/IntelliJ)

Core Spring

Spring Annotations

Spring Data

Spring JDBC

Spring Security

How to Change Default User and Password in Spring Security?

In Spring Security, the default username is "user," and the default password is generated randomly and printed in the console logs during application startup. To change these defaults, you have several options:

Using application.properties or application.yml

You can override the default username and password by specifying them in the application.properties file located in the src/main/resources directory of your Spring Boot project.

# application.properties

spring.security.user.name=myUsername
spring.security.user.password=myPassword

Or, if you're using YAML (application.yml):

# application.yml

spring:
  security:
    user:
      name: myUsername
      password: myPassword

Using WebSecurityConfigurerAdapter

Another way to configure the default user and password is by extending WebSecurityConfigurerAdapter and overriding its configure method:

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .httpBasic();
    }

    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("myUsername")
            .password("myPassword")
            .roles("USER")
            .build();

        return new InMemoryUserDetailsManager(user);
    }
}

Note that using withDefaultPasswordEncoder is not recommended for production use due to its lack of security. This is just for demonstration purposes.

Using Custom Authentication Provider

For more complex scenarios, like fetching user credentials from a database, you can define your own AuthenticationProvider bean:

import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public AuthenticationProvider authenticationProvider() {
        return new AuthenticationProvider() {

            @Override
            public Authentication authenticate(Authentication authentication) throws AuthenticationException {
                String username = authentication.getName();
                String password = authentication.getCredentials().toString();

                if ("myUsername".equals(username) && "myPassword".equals(password)) {
                    return new UsernamePasswordAuthenticationToken(username, password, new ArrayList<>());
                } else {
                    return null;
                }
            }

            @Override
            public boolean supports(Class<?> authentication) {
                return authentication.equals(UsernamePasswordAuthenticationToken.class);
            }
        };
    }
}

Here, you have full control over the authentication logic.

You can choose the most suitable method depending on your use case. The application.properties method is usually appropriate for development and testing, whereas WebSecurityConfigurerAdapter and AuthenticationProvider are better suited for production or more complex scenarios.

  1. Changing Default User and Password in Spring Security:

    • Description: Spring Security provides a default username and password for authentication. You can customize these credentials to enhance security.
    • Code:
      @Configuration
      public class SecurityConfig extends WebSecurityConfigurerAdapter {
          @Override
          protected void configure(AuthenticationManagerBuilder auth) throws Exception {
              auth.inMemoryAuthentication()
                  .withUser("customUser").password("{noop}customPassword").roles("USER");
          }
      }
      
  2. Customizing Default User Credentials in Spring Security:

    • Description: Customize default user credentials by extending WebSecurityConfigurerAdapter and overriding the configure method.
    • Code:
      @Configuration
      public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {
          @Override
          protected void configure(AuthenticationManagerBuilder auth) throws Exception {
              auth.inMemoryAuthentication()
                  .withUser("myUser").password("{noop}myPassword").roles("USER");
          }
      }
      
  3. How to Modify Default Username and Password in Spring Security:

    • Description: Similar to the first point, this emphasizes the modification of default username and password in Spring Security.
    • Code:
      @Configuration
      public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {
          @Override
          protected void configure(AuthenticationManagerBuilder auth) throws Exception {
              auth.inMemoryAuthentication()
                  .withUser("newUser").password("{noop}newPassword").roles("USER");
          }
      }
      
  4. Configuring Custom Authentication in Spring Security:

    • Description: Implement a custom authentication mechanism by extending AbstractAuthenticationProcessingFilter.
    • Code: (Custom AuthenticationFilter)
      public class CustomAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
          // Implementation details
      }
      
  5. Customizing AuthenticationProvider in Spring Security:

    • Description: Customize the authentication provider in Spring Security for more control over user authentication.
    • Code:
      @Bean
      public AuthenticationProvider customAuthenticationProvider() {
          return new CustomAuthenticationProvider();
      }
      
  6. Override Default User and Password in Spring Boot Security:

    • Description: Override default user and password provided by Spring Boot Security.
    • Code:
      spring:
        security:
          user:
            name: customUser
            password: customPassword
      
  7. Spring Security Custom Authentication with Different User Details:

    • Description: Implement a custom UserDetailsService to load user details from a different source.
    • Code:
      @Service
      public class CustomUserDetailsService implements UserDetailsService {
          // Implementation details
      }
      
  8. Modifying AuthenticationManager in Spring Security:

    • Description: Modify the default AuthenticationManager to use a custom authentication provider.
    • Code:
      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.authenticationProvider(customAuthenticationProvider());
      }
      
  9. Custom UserDetailsService in Spring Security:

    • Description: Implement a custom UserDetailsService to load user details from a custom source.
    • Code:
      @Service
      public class CustomUserDetailsService implements UserDetailsService {
          // Implementation details
      }
      
  10. Changing Default Authentication Parameters in Spring Security:

  • Description: Change default authentication parameters like the login URL, success/failure handlers, etc.
  • Code:
    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .formLogin()
                    .loginPage("/custom-login")
                    .successHandler(customSuccessHandler())
                    .failureHandler(customFailureHandler());
        }
    }
    
  1. Spring Security Custom Authentication Provider Example:

    • Description: Implement a custom authentication provider for handling authentication.
    • Code: (Custom AuthenticationProvider)
      public class CustomAuthenticationProvider implements AuthenticationProvider {
          // Implementation details
      }
      
  2. Configuring In-Memory Authentication with Custom User Details:

    • Description: Configure in-memory authentication using custom user details.
    • Code:
      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.userDetailsService(customUserDetailsService());
      }
      
  3. Securing a Spring Boot Application with Custom User Authentication:

    • Description: Secure a Spring Boot application using custom user authentication.
    • Code:
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http
              .authorizeRequests()
                  .antMatchers("/secured-endpoint").hasRole("USER")
                  .and()
              .formLogin();
      }
      
  4. Spring Security Custom Authentication Filters for User Authentication:

    • Description: Implement custom filters for user authentication in Spring Security.
    • Code: (Custom AuthenticationFilter)
      public class CustomAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
          // Implementation details
      }