Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Form-Based Authentication

Form-based authentication in Spring Security provides a customizable way for users to log in to your application. This guide covers key concepts and steps for setting up form-based authentication in your Spring Boot application, including adding dependencies, configuring security, creating login and logout forms, and securing endpoints.

Key Concepts of Form-Based Authentication

  • Form-Based Authentication: A method where users are authenticated through a login form.
  • Login Page: A custom or default page where users enter their credentials.
  • Logout Page: A page or endpoint to log users out of the application.
  • Security Configuration: Configuring Spring Security to use form-based authentication.

Adding Dependencies

Include the Spring Security dependency in your pom.xml file:

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

Configuring Security

Configure security by extending WebSecurityConfigurerAdapter and overriding the configure(HttpSecurity http) method:

Example: SecurityConfiguration.java

// SecurityConfiguration.java
package com.example.myapp.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user")
            .password(passwordEncoder().encode("password"))
            .roles("USER")
            .and()
            .withUser("admin")
            .password(passwordEncoder().encode("admin"))
            .roles("ADMIN");
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/login", "/logout").permitAll()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .defaultSuccessURL("/home", true)
            .failureUrl("/login?error=true")
            .and()
            .logout()
            .logoutSuccessUrl("/login?logout=true")
            .permitAll();
    }
}

Creating Login Form

Create a custom login page to handle user authentication:

Example: login.html

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
    <link rel="stylesheet" type="text/css" href="/css/styles.css" />
</head>
<body>
    <div class="swf-lsn-container">
        <h2>Login</h2>
        <form method="post" action="/login">
            <div>
                <label>Username:</label>
                <input type="text" name="username" />
            </div>
            <div>
                <label>Password:</label>
                <input type="password" name="password" />
            </div>
            <div>
                <input type="submit" value="Login" />
            </div>
        </form>
        <div class="swf-lsn-error-message">
            <#if error?string?trim != "">
                Invalid username or password.
            </#if>
            <#if logout?string?trim != "">
                You have been logged out.
            </#if>
        </div>
    </div>
</body>
</html>

Creating Logout Functionality

Create a logout endpoint to log users out of the application:

Example: SecurityConfiguration.java

// SecurityConfiguration.java
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
        .authorizeRequests()
        .antMatchers("/login", "/logout").permitAll()
        .antMatchers("/admin/**").hasRole("ADMIN")
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .loginPage("/login")
        .defaultSuccessURL("/home", true)
        .failureUrl("/login?error=true")
        .and()
        .logout()
        .logoutSuccessUrl("/login?logout=true")
        .permitAll();
}

Securing Endpoints

Protect specific endpoints by specifying access rules:

Example: SecurityConfiguration.java

// SecurityConfiguration.java
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
        .authorizeRequests()
        .antMatchers("/login", "/logout").permitAll()
        .antMatchers("/admin/**").hasRole("ADMIN")
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .loginPage("/login")
        .defaultSuccessURL("/home", true)
        .failureUrl("/login?error=true")
        .and()
        .logout()
        .logoutSuccessUrl("/login?logout=true")
        .permitAll();
}

Key Points

  • Form-Based Authentication: A method where users are authenticated through a login form.
  • Login Page: A custom or default page where users enter their credentials.
  • Logout Page: A page or endpoint to log users out of the application.
  • Security Configuration: Configuring Spring Security to use form-based authentication.
  • Include the Spring Security dependency in your pom.xml file.
  • Configure security by extending WebSecurityConfigurerAdapter and overriding the configure(HttpSecurity http) method.
  • Create a custom login page to handle user authentication.
  • Create a logout endpoint to log users out of the application.
  • Protect specific endpoints by specifying access rules.

Conclusion

Form-based authentication in Spring Security provides a customizable way for users to log in to your application. By understanding and configuring form-based authentication, security settings, and authentication flows, you can ensure secure access to your application's resources. Happy coding!