Cover Image for Spring Form-Based Authentication
114 views

Spring Form-Based Authentication

Spring Security provides form-based authentication as a common way to authenticate users in web applications. Form-based authentication allows you to create a custom login form that users submit with their credentials. Here are the steps to implement form-based authentication using 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. Configure Spring Security for Form-Based Authentication:

Create a security configuration class that extends WebSecurityConfigurerAdapter and configure Spring Security to use form-based authentication. 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.util.matcher.AntPathRequestMatcher;

@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()
                .and()
            .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/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 configuration above:

  • We configure form-based authentication using .formLogin().
  • We set the custom login page URL to /login with .loginPage("/login").
  • Users are redirected to /login?logout after logging out.
  • 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.

4. Create a Custom Login Page:

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

<!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>

5. Test Form-Based Authentication:

Run your Spring Boot application and access the custom login page (e.g., http://localhost:8080/login). Users will log in using your custom login form.

Form-based authentication 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