Spring Framework Tutorial

Software Setup and Configuration (STS/Eclipse/IntelliJ)

Core Spring

Spring Annotations

Spring Data

Spring JDBC

Spring Security

Spring - Add User Name and Password in Spring Security

To add a username and password for authentication in Spring Security, you can use in-memory authentication, JDBC authentication, or other authentication methods. Here, I'll show you how to add a simple username and password using in-memory authentication and then provide a brief overview of JDBC authentication:

1. In-memory Authentication:

Using in-memory authentication, you can define a user directly in your security configuration:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("username")             // specify the username
                .password(passwordEncoder().encode("password")) // specify the password
                .roles("USER");                   // specify the role
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
            .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
            .and()
            .logout()
                .permitAll();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

In this example, I'm using the BCryptPasswordEncoder to encode the password, which is recommended for security reasons.

2. JDBC Authentication:

For JDBC authentication, Spring Security provides a way to read user credentials directly from the database.

First, add the JDBC driver to your pom.xml:

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

Assuming you have tables users and authorities in your database with schema as Spring Security expects, you can configure JDBC authentication as follows:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .jdbcAuthentication()
            .dataSource(dataSource)
            .usersByUsernameQuery("select username, password, enabled from users where username = ?")
            .authoritiesByUsernameQuery("select username, authority from authorities where username = ?");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
            .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
            .and()
            .logout()
                .permitAll();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

Note: The usersByUsernameQuery and authoritiesByUsernameQuery methods allow you to define custom queries if your schema is different from what Spring Security expects.

Remember:

  1. Always encode your passwords. Never store plain-text passwords in the database or even in your configuration.
  2. For more advanced setups, consider using UserDetailsService where you can provide custom logic for fetching user details.
  3. Ensure to configure other security aspects like CSRF protection, CORS configuration, and session management, according to your application's needs.
  1. Spring Security add user with username and password:

    • To add a user with a username and password, you typically configure a UserDetailsService and provide authentication details.
    @Service
    public class CustomUserDetailsService implements UserDetailsService {
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            // Fetch user details from your data source
            User user = // ... retrieve user details
    
            // Return a UserDetails object with username, password, and authorities
            return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                getAuthorities(user)
            );
        }
    
        private List<GrantedAuthority> getAuthorities(User user) {
            // Retrieve user roles and map them to GrantedAuthorities
            // ...
            return authorities;
        }
    }
    
  2. Configuring user credentials in Spring Security:

    • Configure user credentials by providing a UserDetailsService bean.
    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Autowired
        private CustomUserDetailsService userDetailsService;
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
        }
    
        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    
        // Other configurations...
    }
    
  3. How to set up username and password authentication in Spring Security:

    • Set up username and password authentication by configuring the AuthenticationManagerBuilder.
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user").password("{noop}password").roles("USER")
            .and()
            .withUser("admin").password("{noop}admin").roles("USER", "ADMIN");
    }
    
  4. Adding users to Spring Security with authentication details:

    • Add users to Spring Security by implementing a UserDetailsService and returning authentication details.
    public class CustomUserDetailsService implements UserDetailsService {
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            // Fetch user details from your data source
            User user = // ... retrieve user details
    
            // Return UserDetails with authentication details
            return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                user.getAuthorities()
            );
        }
    }
    
  5. Customizing user authentication in Spring Security:

    • Customize user authentication by providing a custom UserDetailsService and configuring authentication mechanisms.
    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Autowired
        private CustomUserDetailsService userDetailsService;
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder())
                .and()
                .authenticationProvider(customAuthenticationProvider());
        }
    
        @Bean
        public DaoAuthenticationProvider customAuthenticationProvider() {
            DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
            authProvider.setUserDetailsService(userDetailsService);
            authProvider.setPasswordEncoder(passwordEncoder());
            return authProvider;
        }
    
        // Other configurations...
    }
    
  6. Securing Spring application with username and password in Spring Security:

    • Secure your application by configuring authentication based on usernames and passwords.
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/public/**").permitAll()
            .antMatchers("/user/**").hasRole("USER")
            .antMatchers("/admin/**").hasRole("ADMIN")
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .and()
            .httpBasic();
    }
    
  7. Defining user credentials in Spring Security:

    • Define user credentials in a custom UserDetailsService implementation.
    public class CustomUserDetailsService implements UserDetailsService {
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            // Fetch user details from your data source
            User user = // ... retrieve user details
    
            // Define user credentials (username, password, authorities)
            return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                user.getAuthorities()
            );
        }
    }
    
  8. Managing user authentication in Spring Security:

    • Manage user authentication through the UserDetailsService and related configurations.
    @Autowired
    private CustomUserDetailsService userDetailsService;
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
    
  9. Spring Security username and password authentication example:

    • Example of configuring username and password authentication in Spring Security.
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user").password("{noop}password").roles("USER")
            .and()
            .withUser("admin").password("{noop}admin").roles("USER", "ADMIN");
    }