Flat Preloader Icon

Spring Security Custom Login

Creating a custom login page with Spring Security involves creating a custom login form and configuring Spring Security to use it. Here’s how you can create a custom login page with Spring Security step by step:
Create a Custom Login Page: First, create your custom login page (e.g., custom-login.html) using your preferred HTML template engine or technology. Customize the appearance and layout of the login form as needed. Here’s a simple example using HTML:
				
					<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <h2>Login</h2>
<form 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>

				
			
Configure Spring Security: In your Spring Security configuration class (typically named SecurityConfig), configure Spring Security to use your custom login page. You’ll also need to specify the login processing URL and authentication success/failure URLs.
				
					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 = User
        .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("/custom-login")
    // Specify your 
    custom login page URL
    .loginProcessingUrl("/login") 
    // Specify the login
    form submission URL
    .defaultSuccessURL("/dashboard") 
    // Redirect after successful login
    .failureUrl("/custom-login?error=true")
     // Redirect after login failure
    .permitAll().and().logout()
    .logoutUrl("/logout") 
    // Specify the logout URL
    .logoutSuccessUrl("/custom-login") 
    // Redirect after logout
    .permitAll();
    }
}

				
			

In this configuration:

  • We define a custom login page URL using .loginPage("/custom-login").
  • We specify the URL where the login form will be submitted using .loginProcessingUrl("/login").
  • We set the default success URL after a successful login using .defaultSuccessURL("/dashboard").
  • We specify the URL to redirect to after a login failure using .failureUrl("/custom-login?error=true").
  • We define a custom logout URL using .logoutUrl("/logout") and specify the logout success URL using .logoutSuccessUrl("/custom-login").

Customize User Authentication: Depending on your application, you may need to customize how users are authenticated. In the example above, we’re using an in-memory user details manager with a single user. For a real-world application, you should implement a custom UserDetailsService to load user details from your data source (e.g., a database).

Create Controller and Redirect to Custom Login Page (Optional):You may need to create a controller to handle the URL mapped to your custom login page. This controller can simply return the custom login page template.

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

@Controller
public class CustomLoginController {

    @GetMapping("/custom-login")
    public String customLogin() {
        return "custom-login";
    }
}

				
			

Customize and Style Your Custom Login Page:

Customize the appearance and style of your custom login page according to your application’s design requirements.

With these steps, you’ve created a custom login page with Spring Security. Users will be directed to your custom login page when they attempt to access a secured resource, and the form submission will be processed by Spring Security’s authentication mechanism. Customize the configuration and user authentication process further to meet your application’s specific needs.

Share on: