Form-based login lets users enter their username and password on a webpage to access a secure area. It makes login easy and user-friendly.
Form-based login configuration in Spring Boot
http
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.failureUrl("/login?error")
.permitAll()formLogin() enables form-based login in Spring Security.
loginPage() sets the URL of your custom login page.
http .formLogin()
/custom-login and allows everyone to access it.http
.formLogin()
.loginPage("/custom-login")
.permitAll()http
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/dashboard")
.failureUrl("/login?error")
.permitAll()This example shows how to configure Spring Security to use a custom login page at /login. The SecurityConfig class sets up the form login with success and failure URLs. The LoginController serves the login page. The login form posts credentials to /login for authentication.
import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class LoginController { @GetMapping("/login") public String login() { return "login"; // returns login.html view } } @Configuration public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers("/login", "/css/**").permitAll() .anyRequest().authenticated() ) .formLogin(form -> form .loginPage("/login") .defaultSuccessUrl("/home", true) .failureUrl("/login?error") .permitAll() ); return http.build(); } } // login.html (Thymeleaf template example) // <html> // <body> // <form action="/login" method="post"> // <label for="username">Username:</label> // <input type="text" id="username" name="username" /> // <label for="password">Password:</label> // <input type="password" id="password" name="password" /> // <button type="submit">Log In</button> // <div th:if="${param.error}">Invalid username or password.</div> // </form> // </body> // </html>
Always allow everyone to access the login page using permitAll() so users can reach it.
Use defaultSuccessUrl with true as second argument to always redirect after login.
Customize the login page HTML to improve user experience and accessibility.
Form-based login lets users sign in via a webpage you control.
Configure it in Spring Security with formLogin() and set your login page URL.
Handle success and failure redirects to guide users after login attempts.