Cover Image for Spring Security Custom Login
177 views

Spring Security Custom Login

Customizing the login functionality in Spring Security allows you to create a login page with your custom design and behavior. You can achieve this by configuring Spring Security to use your custom login page and handling authentication requests. Here’s a step-by-step guide to creating a custom login page with Spring Security in a Spring Boot application:

1. Create a Spring Boot Project:

If you haven’t already, create a Spring Boot project or use an existing one.

2. Add Spring Security Dependency:

In your project’s pom.xml (if using Maven) or build.gradle (if using Gradle), make sure you have the Spring Security dependency:

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

3. Create a Custom Login Page:

Create a custom login page (e.g., custom-login.html) in your project’s src/main/resources/templates directory. Customize the page according to your design and requirements. For example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <h2>Login</h2>
    <form action="/login" method="post">
        <div>
            <label for="username">Username</label>
            <input type="text" id="username" name="username" required>
        </div>
        <div>
            <label for="password">Password</label>
            <input type="password" id="password" name="password" required>
        </div>
        <div>
            <button type="submit">Login</button>
        </div>
    </form>
</body>
</html>

4. Configure Spring Security for Custom Login:

Create a security configuration class that extends WebSecurityConfigurerAdapter and configure Spring Security to use your custom login page. Define authentication and authorization rules as needed.

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.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.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/public/**").permitAll() // Allow access to public resources without authentication
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login") // Set custom login page URL
                .permitAll()
                .successHandler(new SimpleUrlAuthenticationSuccessHandler("/dashboard")) // Redirect after successful login
                .and()
            .logout()
                .logoutUrl("/logout")
                .permitAll()
                .logoutSuccessUrl("/login?logout"); // Redirect after logout
    }

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

        return new InMemoryUserDetailsManager(user);
    }
}

In the example above:

  • We configure the custom login page URL using .loginPage("/login").
  • After a successful login, users are redirected to the /dashboard URL.
  • After logging out, users are redirected to the /login?logout URL.
  • The userDetailsService() method defines a simple in-memory user for testing purposes. In a real application, you’d typically use a more robust authentication mechanism.

5. Test Your Custom Login Page:

Now, you can run your Spring Boot application and access your custom login page (e.g., http://localhost:8080/login). Users will log in using your custom-designed login form.

Customizing the login page in Spring Security allows you to create a user-friendly and branded login experience while still benefiting from Spring Security’s authentication and security features.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS