📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this Spring Security tutorial, we will learn how to use Spring Security provided built-in Form-Based Authentication.
Spring Security provides support for username and password is provided through an HTML form.
Form-Based Authentication Overview
Form-based authentication uses standard HTML form (Login Form) fields to pass the username and password values to the server via a POST request.
In Form-based authentication, the server validates the credentials provided and creates a “session” tied to a unique token stored in a cookie and passed between the client and the server on each HTTP request. If the cookie is invalid or the user is logged out, the server then usually redirects to a login page.
Maven Dependencies
In order to implement Spring Security provided built-in Form-Based Authentication, we need to add below two Maven dependencies:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
Note that we are using Thymeleaf to create a simple template welcome.html that we return that template after login success.
Spring Security Configuration
By default, Spring Security form login is enabled. However, as soon as any servlet-based configuration is provided, form-based login must be explicitly provided.
The below configuration shows a minimal, explicit Java configuration:
@Bean SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeHttpRequests((authorize) -> { authorize.anyRequest().authenticated(); }).formLogin(Customizer.withDefaults()); return http.build(); }
In order to test the form-based authentication, let's create a couple of in-memory objects. In the below InMemoryUserDetailsManager Java Configuration, we have created two users and stored them in the InMemoryUserDetailsManager class object.
@Bean public UserDetailsService userDetailsService(){ UserDetails ramesh = User.builder() .username("ramesh") .password(passwordEncoder().encode("password")) .roles("USER") .build(); UserDetails admin = User.builder() .username("admin") .password(passwordEncoder().encode("admin")) .roles("ADMIN") .build(); return new InMemoryUserDetailsManager(ramesh, admin); }
We are using
BCryptPasswordEncoder class which implements the
PasswordEncoder interface. The
BCryptPasswordEncoder class implementation uses the widely supported
bcrypt algorithm to hash the passwords.
@Bean public static PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); }
.password(passwordEncoder().encode("password"))
Here is the complete Spring Security configuration code:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; 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.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.SecurityFilterChain; @Configuration public class SpringSecurityConfig { @Bean public static PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } @Bean SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeHttpRequests((authorize) -> { authorize.anyRequest().authenticated(); }).formLogin(Customizer.withDefaults()); return http.build(); } @Bean public UserDetailsService userDetailsService(){ UserDetails ramesh = User.builder() .username("ramesh") .password(passwordEncoder().encode("password")) .roles("USER") .build(); UserDetails admin = User.builder() .username("admin") .password(passwordEncoder().encode("admin")) .roles("ADMIN") .build(); return new InMemoryUserDetailsManager(ramesh, admin); } }
Create WelcomeController and Thymeleaf Template
WelcomeController
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class WelComeController { @GetMapping("/") public String greeting() { return "welcome"; } }
Thymeleaf Template - welcome.html
Under /resources/templates folder, create a welcome.html file and add the following content:
<html> <body> <h1> Welcome to Spring Security world!</h1> </body> </html>
Use Spring Security's Default Login Page
By default, Spring Security provides a built-in Login form to secure the web application:
Test using Browser
Enter
http://localhost:8080 URL in the browser and it will navigate to the login page. Next, enter a username as
admin, password as
admin, and click on the Sign-in button:
After successful login, you will see the below web page:
Built-In Logout Feature
Spring Security provided a built-in logout feature as well. Just enter
http://localhost:8080/logout URL in the browser to logout from the application:
Conclusion
In this tutorial, we have seen how to configure Spring Security's built-in form-based authentication to secure a simple web page.
Related Spring Security Tutorials/Guides:
Core Components of Spring Security Spring Security: Authentication Spring Security: Authorization Spring Security: Principal Spring Security: Granted Authority Spring Security: SecurityContextHolder Spring Security: UserDetailsService Spring Security: Authentication Manager Spring Security: Authentication Provider Spring Security: Password Encoder AuthenticationEntryPoint in Spring Security @PreAuthorize Annotation in Spring Security Spring Security Basic Authentication Spring Security In-Memory Authentication Spring Security Form-Based Authentication Difference Between Basic Authentication and Form Based Authentication Spring Security Custom Login Page Spring Security Login Form Example with Database Authentication Spring Boot Login REST API Login and Registration REST API using Spring Boot, Spring Security, Hibernate, and MySQL Database Spring Boot + Spring Security + Angular Example Tutorial Spring Boot + Angular Login Authentication, Logout, and HttpInterceptor Example Spring Security In-Memory Authentication Example Spring Security Hibernate Database Authentication - UserDetailsService Securing a Spring MVC Application with Spring Security Spring Boot Security Login REST API Example Spring Boot Security Login and Registration REST API Role-based Authorization using Spring Boot and Spring Security Spring Boot Security JWT Token-Based Authentication and Role-Based Authorization Tutorial Spring Boot + Spring Security + JWT + MySQL Database Tutorial Spring Boot JWT Authentication and Authorization Example Spring Boot Security JWT Example - Login REST API with JWT Authentication Spring Boot Security JWT Token-Based Authentication and Role-Based Authorization Tutorial Spring Security - Get Current Logged-In User Details Spring Security - How to Get Current Logged-In Username in JSP Spring Security - How to Access User Roles in JSP Spring Security - How to Get Current Logged-In Username in Themeleaf Spring Security Tutorial - Registration, Login, and Logout Spring Boot 2 + Spring MVC + Role-Based Spring Security + JPA + Thymeleaf + MySQL Tutorial User Registration Module using Spring Boot 2 + Spring MVC + Spring Security + Hibernate 5 + Thymeleaf + MySQL Registration and Login using Spring Boot, Spring Security, Spring Data JPA, Hibernate, H2, JSP, and Bootstrap Spring Boot User Registration and Login Example Tutorial
Comments
Post a Comment
Leave Comment