How to Create Login in Spring Security: Simple Guide
To create a login in
Spring Security, configure a security filter chain with HttpSecurity to enable form login and define user details. Use SecurityFilterChain bean to set login page, success, and failure handlers, and provide user credentials via UserDetailsService or in-memory users.Syntax
The main syntax involves defining a SecurityFilterChain bean where you configure HTTP security settings. You enable form login with http.formLogin() and set user details with a UserDetailsService bean.
http.formLogin(): Enables login form support.http.authorizeHttpRequests(): Defines which URLs require authentication.UserDetailsService: Provides user credentials and roles.
java
import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.SecurityFilterChain; @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .anyRequest().authenticated() ) .formLogin(form -> form .loginPage("/login") .permitAll() ) .logout(logout -> logout.permitAll()); return http.build(); } @Bean public UserDetailsService users() { return new InMemoryUserDetailsManager( User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build() ); }
Example
This example shows a minimal Spring Security setup with an in-memory user and a custom login page at /login. It secures all URLs and allows users to log in with username "user" and password "password".
java
package com.example.securitydemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.SecurityFilterChain; @SpringBootApplication public class SecurityDemoApplication { public static void main(String[] args) { SpringApplication.run(SecurityDemoApplication.class, args); } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .anyRequest().authenticated() ) .formLogin(form -> form .loginPage("/login") .permitAll() ) .logout(logout -> logout.permitAll()); return http.build(); } @Bean public UserDetailsService users() { return new InMemoryUserDetailsManager( User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build() ); } }
Output
When running the application, accessing any URL redirects to /login page. Entering username 'user' and password 'password' logs in successfully and grants access.
Common Pitfalls
Common mistakes when creating login in Spring Security include:
- Not defining a
UserDetailsServiceor user credentials, causing authentication failures. - Forgetting to permit access to the login page, which causes infinite redirect loops.
- Using deprecated password encoders or storing passwords in plain text without encoding.
- Not calling
http.build()at the end of the security configuration.
Always ensure your login page URL is permitted for all users and passwords are encoded.
java
/* Wrong: No permitAll on login page causes redirect loop */ http .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) .formLogin(form -> form.loginPage("/login")); // missing permitAll() /* Right: Permit all users to access login page */ http .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) .formLogin(form -> form.loginPage("/login").permitAll());
Quick Reference
Tips for creating login in Spring Security:
- Use
SecurityFilterChainbean to configure HTTP security. - Enable form login with
http.formLogin()and set a custom login page if needed. - Define users with
UserDetailsService, preferably with password encoding. - Permit access to login and logout URLs to avoid redirect issues.
- Test login flow by accessing a secured URL and verifying redirection to login page.
Key Takeaways
Configure a SecurityFilterChain bean to enable form login and secure URLs.
Provide user credentials via UserDetailsService with encoded passwords.
Always permit all users to access the login page to avoid redirect loops.
Use http.build() to finalize security configuration.
Test login by accessing secured pages and verifying authentication flow.