Spring Boot Tutorial

Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)

Prerequisite (Spring Core Concepts)

Spring Boot Core

Spring Boot with REST API

Spring Boot with Database and Data JPA

Spring Boot with Kafka

Spring Boot with AOP

How to Implement Simple Authentication in Spring Boot?

To implement simple authentication in a Spring Boot application, you can use Spring Security. Here's a basic walkthrough of how to set up a simple username and password-based authentication:

1. Add Dependencies:

Add the required Spring Security dependencies to your pom.xml:

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

2. Configure Spring Security:

Spring Security provides default security settings (e.g., a default user with a generated password). To customize these settings, you can create a configuration class:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable() // You might want to disable CSRF for simplicity, but it's a security feature you should consider enabling in production
            .authorizeRequests()
                .antMatchers("/public/**").permitAll() // Public URLs
                .anyRequest().authenticated() // All other URLs are secured
            .and()
            .httpBasic(); // Use basic authentication
    }

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

3. Define a UserDetailsService:

The UserDetailsService interface provides a way to retrieve user-related data. You can implement this to provide users and roles:

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.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // In this simple example, only a single user is supported.
        // In a real-world scenario, you would fetch the user from a database or another external source.
        if ("user".equals(username)) {
            return User
                    .withUsername("user")
                    .password(passwordEncoder().encode("password")) // Always encode passwords!
                    .roles("USER")
                    .build();
        } else {
            throw new UsernameNotFoundException("User not found");
        }
    }

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

4. Run the Application:

When you run your Spring Boot application, Spring Security will secure all endpoints by default. You can use the default username (user) and the generated password (printed in the console on startup) to access your application.

For any endpoint under /public/, no authentication is required (as per our configuration). For all other endpoints, you'll be prompted for a username and password.

This is a very basic authentication setup. In real-world applications, you would typically integrate with a database to fetch user details, handle user registration, use form-based login, and possibly add OAuth2 or JWT-based authentication. Always ensure you follow security best practices when implementing authentication and authorization in your applications.

  1. Configuring basic username and password authentication in Spring Boot:

    • Description: Set up basic authentication with username and password in a Spring Boot application.
    • Java Code (SecurityConfig.java):
      @Configuration
      @EnableWebSecurity
      public class SecurityConfig extends WebSecurityConfigurerAdapter {
          @Override
          protected void configure(AuthenticationManagerBuilder auth) throws Exception {
              auth.inMemoryAuthentication()
                  .withUser("user").password("{noop}password").roles("USER");
          }
      
          // Other security configurations
      }
      
  2. Creating a login page for simple authentication in Spring Boot:

    • Description: Develop a login page for users to authenticate in a Spring Boot application.
    • HTML Code (login.html):
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>Login Page</title>
      </head>
      <body>
          <form action="/login" method="post">
              <label for="username">Username:</label>
              <input type="text" id="username" name="username" required>
              <br>
              <label for="password">Password:</label>
              <input type="password" id="password" name="password" required>
              <br>
              <button type="submit">Login</button>
          </form>
      </body>
      </html>
      
  3. Setting up an authentication provider in Spring Boot:

    • Description: Configure an authentication provider for advanced authentication options.

    • Java Code (CustomAuthenticationProvider.java):

      @Component
      public class CustomAuthenticationProvider implements AuthenticationProvider {
          // Implementation of authenticate method
      }
      
    • Java Code (SecurityConfig.java):

      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.authenticationProvider(new CustomAuthenticationProvider());
      }
      
  4. Securing endpoints with basic authentication in Spring Boot:

    • Description: Secure specific endpoints with basic authentication in a Spring Boot application.
    • Java Code (SecurityConfig.java):
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http.authorizeRequests()
              .antMatchers("/secured-endpoint").authenticated()
              .anyRequest().permitAll()
              .and()
              .httpBasic();
      }
      
  5. Customizing login forms and authentication filters in Spring Boot:

    • Description: Customize login forms and authentication filters for a personalized authentication experience.
    • Java Code (SecurityConfig.java):
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http.formLogin()
              .loginPage("/custom-login")
              .usernameParameter("custom-username")
              .passwordParameter("custom-password")
              .and()
              .addFilterBefore(new CustomAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
      }
      
  6. Handling user roles and authorities in Spring Boot authentication:

    • Description: Manage user roles and authorities for fine-grained access control in Spring Boot authentication.
    • Java Code (CustomAuthenticationProvider.java):
      @Override
      public Collection<? extends GrantedAuthority> getAuthorities() {
          // Return a list of authorities based on user roles
      }
      
  7. Storing user credentials securely with Spring Boot:

    • Description: Implement secure storage mechanisms for user credentials in a Spring Boot application.
    • Java Code (SecurityConfig.java):
      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
      }
      
  8. Configuring remember-me authentication in Spring Boot:

    • Description: Enable remember-me authentication to persist user sessions across browser sessions.
    • Java Code (SecurityConfig.java):
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http.rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400);
      }
      
  9. Implementing session management for simple authentication in Spring Boot:

    • Description: Implement session management strategies for handling user sessions in Spring Boot.
    • Java Code (SecurityConfig.java):
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http.sessionManagement().maximumSessions(1).sessionRegistry(sessionRegistry());
      }
      
  10. Integrating Spring Security for simple authentication:

    • Description: Integrate Spring Security to leverage its features for authentication in a Spring Boot application.
    • Java Code (pom.xml):
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-security</artifactId>
      </dependency>
      
  11. Implementing stateless token-based authentication in Spring Boot:

    • Description: Implement stateless authentication using tokens for RESTful services in Spring Boot.
    • Java Code (JwtTokenProvider.java):
      public class JwtTokenProvider {
          // Token creation and validation methods
      }
      
  • Java Code (SecurityConfig.java):
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.apply(new JwtConfigurer(jwtTokenProvider));
    }
    
  1. Handling authentication failures and errors in Spring Boot:

    • Description: Handle authentication failures and errors gracefully in a Spring Boot application.
    • Java Code (SecurityConfig.java):
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http.exceptionHandling().authenticationEntryPoint(customAuthenticationEntryPoint);
      }
      
  2. Customizing success and failure handlers in Spring Boot authentication:

    • Description: Customize success and failure handlers for tailored responses in Spring Boot authentication.

    • Java Code (CustomAuthenticationSuccessHandler.java and CustomAuthenticationFailureHandler.java):

      public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
          // Implementation of onAuthenticationSuccess method
      }
      
      public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
          // Implementation of onAuthenticationFailure method
      }
      
    • Java Code (SecurityConfig.java):

      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http.formLogin()
              .successHandler(customAuthenticationSuccessHandler)
              .failureHandler(customAuthenticationFailureHandler);
      }
      
  3. Enforcing HTTPS for secure authentication in Spring Boot:

    • Description: Enforce the use of HTTPS for secure communication in a Spring Boot authentication setup.
    • Java Code (SecurityConfig.java):
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http.requiresChannel().anyRequest().requiresSecure();
      }
      
  4. Configuring authentication providers with LDAP in Spring Boot:

    • Description: Configure authentication providers using LDAP for centralized authentication in Spring Boot.
    • Java Code (SecurityConfig.java):
      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.ldapAuthentication()
              .userDnPatterns("uid={0},ou=people")
              .groupSearchBase("ou=groups");
      }
      
  5. Implementing two-factor authentication in Spring Boot:

    • Description: Implement two-factor authentication for an extra layer of security in Spring Boot.

    • Java Code (TwoFactorAuthenticationProvider.java):

      public class TwoFactorAuthenticationProvider implements AuthenticationProvider {
          // Implementation of authenticate method for two-factor authentication
      }
      
    • Java Code (SecurityConfig.java):

      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.authenticationProvider(twoFactorAuthenticationProvider);
      }