Flat Preloader Icon

Spring Security Based Authentication

Spring Security provides built-in support for form-based authentication, allowing you to create login pages and handle user authentication using a web form. Here’s how to implement form-based authentication with Spring Security:

Create a Spring Boot Project: Start by creating a Spring Boot project using your preferred IDE or Spring Initializer. Make sure to include the “Spring Web” and “Spring Security” dependencies.

Configure Spring Security: Create a configuration class that extends WebSecurityConfigurerAdapter to configure Spring Security. Define your security rules, including form-based authentication.

				
					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.core
.userdetails.User;
import org.springframework
.security.core
.userdetails.UserDetails;
import org.springframework
.security.core
.userdetails
.UserDetailsService;
import org.springframework
.security.provisioning
.InMemoryUserDetailsManager;
import org.springframework
.security.config.annotation
.authentication.builders
.AuthenticationManagerBuilder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends
WebSecurityConfigurerAdapter {

    @Bean
    @Override
public UserDetailsService 
userDetailsService() {
UserDetails user
= Use.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
 return new 
 InMemoryUserDetailsManager(user);
    }

    @Override
    protected void configure
    (HttpSecurity http) 
    throws Exception {
http.authorizeRequests()
.antMatchers("/public/**").permitAll()
.antMatchers("/private/**")
.authenticated()
.and().formLogin()
.loginPage("/login")
//Customize the login page URL
.defaultSuccessURL("/dashboard") 
// Redirect after successful login
.permitAll().and().logout()
.logoutUrl("/logout")
                
.logoutSuccessUrl("/login") 
                
                .permitAll();
    }
}

				
			

In this example:

  • We define an in-memory user with the username “user” and password “password” for demonstration purposes. In a real application, you should load user details from a database or another source.
  • We configure form-based authentication using .formLogin().
  • We specify the custom login page URL using .loginPage("/login").
  • We set the default success URL after a successful login using .defaultSuccessURL("/dashboard").
  • We define a custom logout URL using .logoutUrl("/logout") and specify the logout success URL using .logoutSuccessUrl("/login").

Create a Login Page: Create an HTML login page (e.g., login.html) in your project’s templates directory. Customize it to match your application’s design and include a form that posts to the login URL.

				
					<!DOCTYPE html>
<html xmlns:th
="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <h2>Login</h2>
    <form th:action
    ="@{/login}" method="post">
        <label for
        ="username">Username:</label>
<input type
="text" id="username" 
 name="username" required autofocus>
        <br>
<label for
="password">Password:</label>
<input type
="password" id="password" 
name="password" required>
        <br>
<button type
="submit">Login</button>
    </form>
</body>
</html>

				
			

Secure Your Application: Use security annotations or configuration to protect specific parts of your application. For example, you can use @PreAuthorize annotations on your controller methods to restrict access to certain roles or users.

Customize User Authentication: Depending on your application, you may need to customize how users are authenticated. In the example above, we used an in-memory user details manager. For a real-world application, implement a custom UserDetailsService to load user details from a database or another data source.

Create a Logout Controller (Optional): If you want to create a custom logout button or page, you can create a controller method for handling logout.

				
					import org.springframework
.stereotype.Controller;
import org.springframework
.web.bind.annotation.GetMapping;

@Controller
public class LogoutController {

    @GetMapping("/logout")
    public String logout() {
        // Perform logout operations
        return "redirect:/login";
    }
}

				
			
  1. In this example, the /logout endpoint performs the logout operation and redirects the user to the login page.

With these steps, you’ve implemented form-based authentication with Spring Security in your Spring Boot application. Customize the configuration and user authentication process to fit your specific application requirements.

Share on: