Form Login Authentication
Form-based login, custom login pages, session management, remember-me, CSRF
- Configure form login with custom login and logout URLs
- Enable remember-me authentication with a persistent token repository
- Understand CSRF protection and when to disable it for APIs
A complete, professional study guide based on the "Concept and Coding" Spring Boot Security lecture series — Form Login Authentication.
Table of Contents
- Why Study Form Login Before JWT?
- What is Form Login Authentication?
- Stateful vs Stateless Authentication
- What is an HTTP Session?
- Session Storage — Memory vs Database
- Configuring Session Timeout
- Storing Sessions in the Database
- End-to-End Flow — Step 1: Login (Session Creation)
- End-to-End Flow — Step 2: Accessing a Protected Resource
- Why Zero Code is Needed for Basic Form Login
- Custom Security Filter Chain Configuration
- Authorization Filter
- Two Phases of Authorization
- Session Management Controls
- Session Creation Policy
- Disadvantages of Form Login Authentication
- Diagrams
- Key Observations
- Common Mistakes
- Best Practices
- Interview Notes
- Comparison Tables
- Practice Questions
- Summary
1. Why Study Form Login Before JWT?
Form login is the default authentication method in Spring Boot Security and the historical foundation on which modern stateless methods like JWT and OAuth were built. Studying it first answers:
- What problem does "maintaining state" solve?
- What are the costs of server-side session management?
- Why did the industry move toward stateless tokens (JWT)?
- What does the Security Filter Chain actually do under the hood?
2. What is Form Login Authentication?
Overview
Form login is a stateful authentication mechanism where a user submits their credentials once via an HTML login form. On success, the server creates and maintains a session representing that user's authenticated state. Subsequent requests carry only a session ID — not credentials — and the server validates the session on each call.
Defining Characteristics
- Stateful — the server maintains the user's authentication state between requests.
- Session-based — after login, a session is the proof of identity.
- Default — it is the default authentication method in Spring Boot Security. No configuration is needed to activate it.
- Default URLs — Spring Boot provides
/loginand/logoutendpoints automatically.
Default Login and Logout URLs
| URL | Purpose |
|---|---|
/login | Default login page. Accepts username and password via HTML form POST. |
/logout | Invalidates the current session and logs the user out. |
3. Stateful vs Stateless Authentication
Stateful Authentication (Form Login)
The server keeps track of every authenticated user's state in memory or a database (as a session). Each request is validated by looking up the server-side session.
1Client Server2 | |3 |--- POST /login (user+pass) -->|4 | |--- create session, store it5 |<-- Set-Cookie: JSESSIONID ----|6 | |7 |--- GET /users (cookie) ------>|8 | |--- look up session, validate9 |<-- 200 OK ---------------------|Stateless Authentication (e.g., JWT)
The token itself carries all authentication information. The server does not store any session. Every request is self-contained.
1Client Server2 | |3 |--- POST /login (user+pass) -->|4 |<-- JWT Token ------------------|5 | |6 |--- GET /users (Bearer token)->|7 | |--- verify token signature8 |<-- 200 OK ---------------------|Key Difference
| Aspect | Stateful (Form Login) | Stateless (JWT) |
|---|---|---|
| Session stored | On server (memory/DB) | Not stored (in token) |
| Server memory usage | High (scales with users) | None |
| Logout behavior | Invalidate server session | Client discards token |
| Distributed systems | Requires shared session store (DB) | No shared store needed |
| Scalability | Harder | Easier |
4. What is an HTTP Session?
Definition
An HTTP session is a server-side object (HttpSession) that stores data associated with a specific user across multiple HTTP requests. Since HTTP is stateless by nature, sessions are the mechanism by which a server "remembers" a user between requests.
What an HttpSession Object Contains
| Field | Description |
|---|---|
| Session ID | A unique identifier (e.g., ABC123XYZ) assigned when the session is created |
| Creation Time | Timestamp when the session was first created |
| Last Accessed Time | Timestamp of the most recent request that used this session |
| Max Inactive Interval | Inactivity duration (in seconds) after which the session expires |
| Expiry Time | Computed as: last accessed time + max inactive interval |
| Principal Name | The username of the authenticated user |
| Security Context | The serialized Spring Security SecurityContext (holds Authentication object with roles, etc.) |
Session Lifecycle
1User sends credentials2 ↓3Server authenticates user4 ↓5Server creates HttpSession object (new unique session ID)6 ↓7SecurityContext stored inside HttpSession8 ↓9Session stored in memory or DB10 ↓11Session ID sent to client in Set-Cookie header12 ↓13Client sends session ID in cookie on every subsequent request14 ↓15Server looks up HttpSession by session ID16 ↓17If found and valid: fulfill request18If not found or expired: redirect to /loginSession Expiry Inactivity Based
If a user continues making requests, the session's expiry time is continuously extended. The session only expires after a defined period of complete inactivity.
1Session created: 12:002Timeout: 5 minutes3
412:00 → session created512:03 → user makes a request → last access updated → expires at 12:08612:06 → user makes a request → last access updated → expires at 12:11712:16 → (no activity for 5 min) → session EXPIRED5. Session Storage Memory vs Database
Default: In-Memory (Servlet Container)
By default, the HttpSession object is stored inside the servlet container (e.g., Tomcat's in-process memory). This is fast and requires no additional setup, but has a critical flaw in distributed deployments.
The Problem with In-Memory Sessions in Distributed Systems
1Load Balancer2 ↓3┌───────────┐ ┌───────────┐4│ Server 1 │ │ Server 2 │5│ Session A │ │ (no sess) │6└───────────┘ └───────────┘7
8Client logs in → request goes to Server 1 → session created on Server 19Client's next request → load balancer routes to Server 2 → session not found → 401 / redirect to loginThis is a bad user experience — the user is forced to log in again even though they already authenticated.
Solution: Database-Backed Session Storage
Store HttpSession data in a shared database that all server instances can access.
1Load Balancer2 ↓3┌───────────┐ ┌───────────┐4│ Server 1 │ │ Server 2 │5└───────────┘ └───────────┘6 ↘ ↙7 ┌──────────┐8 │ Session │9 │ Database │10 └──────────┘11
12Any server can now validate any session!spring-session-jdbc) or a cache like Redis (via spring-session-data-redis).6. Configuring Session Timeout
In `application.properties`
1# Set session inactivity timeout to 5 minutes (default is 30 minutes)2server.servlet.session.timeout=5m3
4# Or in seconds:5server.servlet.session.timeout=3007. Storing Sessions in the Database
Required Dependency
1<!-- pom.xml -->2<dependency>3 <groupId>org.springframework.session</groupId>4 <artifactId>spring-session-jdbc</artifactId>5</dependency>`application.properties` Configuration
1# Tell Spring Boot to create the session tables automatically2spring.session.jdbc.initialize-schema=always3
4# Use JDBC as the session store5spring.session.store-type=jdbc6
7# Session timeout (5 minutes)8server.servlet.session.timeout=5mTables Created by Spring Boot
When initialize-schema=always is set, Spring Boot automatically creates two tables:
◆ `SPRING_SESSION`
| Column | Description |
|---|---|
PRIMARY_ID | Internal primary key |
SESSION_ID | The unique session identifier sent to the client |
CREATION_TIME | Epoch millis when session was created |
LAST_ACCESS_TIME | Epoch millis of last request using this session |
MAX_INACTIVE_INTERVAL | Inactivity timeout in seconds (e.g., 300 for 5 min) |
EXPIRY_TIME | last_access_time + max_inactive_interval — auto-updated on each request |
PRINCIPAL_NAME | Username of the authenticated user |
◆ `SPRING_SESSION_ATTRIBUTES`
Stores serialized attributes attached to the session. The most important attribute is:
| Attribute Name | Value |
|---|---|
SPRING_SECURITY_CONTEXT | Serialized SecurityContext object (contains Authentication data: username, roles, etc.) |
EXPIRY_TIME column is continuously updated on each user request. Spring Boot increments it by MAX_INACTIVE_INTERVAL from the LAST_ACCESS_TIME. This is how inactivity-based expiry works.8. End-to-End Flow Step 1: Login (Session Creation)
Scenario
A user hits /login with their username and password for the first time. No session exists yet.
Step-by-Step Execution
◆ Stage 1: Request Reaches Security Filter Chain
1POST /login2 username: "user"3 password: "pass"4 _csrf: "<token>"5 ↓6Servlet Container7 ↓8General Filter Chain9 ↓10Security Filter Chain → UsernamePasswordAuthenticationFilter invoked◆ Stage 2: Authentication Object Created
UsernamePasswordAuthenticationFilter creates a UsernamePasswordAuthenticationToken — a concrete implementation of the Authentication interface:
1{2 "principal": "user",3 "credentials": "pass",4 "authorities": [],5 "isAuthenticated": false6}This partial, unauthenticated object is passed to AuthenticationManager.
◆ Stage 3: AuthenticationManager DaoAuthenticationProvider
ProviderManager (the default AuthenticationManager) receives the object and delegates to DaoAuthenticationProvider.
DaoAuthenticationProvider performs:
- Hash the incoming password using the configured
PasswordEncoder(e.g., BCrypt). - Load the stored user via
UserDetailsService.loadUserByUsername("user")— fetches username, stored hashed password, and roles from the data source. - Compare passwords —
passwordEncoder.matches(rawPassword, storedHash). - If matched: update the
Authenticationobject to fully authenticated:
1{2 "principal": {3 "username": "user",4 "enabled": true,5 "accountNonExpired": true,6 "credentialsNonExpired": true7 },8 "credentials": null,9 "authorities": ["ROLE_USER"],10 "isAuthenticated": true11}Authentication object after successful authentication. It is set to null for security.◆ Stage 4: SecurityContextHolderFilter Security Context Created
The filter receives the fully authenticated Authentication object and:
- Creates a
SecurityContextobject. - Stores the
Authenticationinside theSecurityContext.
◆ Stage 5: HttpSessionSecurityContextRepository Session Created
The SecurityContext is passed to HttpSessionSecurityContextRepository, which:
- Creates a new
HttpSessionobject with a unique session ID. - Stores the
SecurityContextinside theHttpSession(serialized asSPRING_SECURITY_CONTEXT). - Persists the
HttpSession— in memory (default) or in the database (ifspring-session-jdbcis configured).
◆ Stage 6: Session ID Sent to Client
The session ID is set in the HTTP response as a cookie:
1HTTP/1.1 200 OK2Set-Cookie: JSESSIONID=ABC123XYZ; Path=/; HttpOnly◆ Stage 7: Controller Invoked
After the security filter chain completes successfully:
- The request proceeds to the Dispatcher Servlet.
- If the login endpoint (
/login) was used, Spring redirects to the default page (/). - If the user was trying to access a protected resource directly (e.g.,
/users), Spring redirects them to that resource after login.
9. End-to-End Flow Step 2: Accessing a Protected Resource
Scenario
The user has already logged in and has a valid session cookie. They now call /users.
Step-by-Step Execution
◆ Stage 1: Request Arrives With Session Cookie
1GET /users2Cookie: JSESSIONID=ABC123XYZ◆ Stage 2: SecurityContextHolderFilter Invoked (NOT UsernamePasswordAuthenticationFilter)
For subsequent requests, UsernamePasswordAuthenticationFilter is skipped — the user is not submitting credentials. Instead, SecurityContextHolderFilter handles the request.
It passes the session ID to HttpSessionSecurityContextRepository to look up the session.
◆ Stage 3: Session Lookup
HttpSessionSecurityContextRepository:
- Reads the
JSESSIONIDcookie from the request. - Looks up the
HttpSessionwith that ID — from in-memory or database. - If not found or expired → redirects to
/login. - If found and valid → extracts the
SecurityContextfrom the session.
◆ Stage 4: SecurityContext Populated for Request Lifecycle
The retrieved SecurityContext (containing the fully authenticated Authentication object with username and roles) is stored in SecurityContextHolder. It is available throughout the entire request lifecycle — in filters, interceptors, and controllers.
◆ Stage 5: Authorization Filter
Before the request reaches the controller, the Authorization Filter checks:
- What resource is being accessed? (
/users) - What role does this resource require? (from your
SecurityFilterChainconfig) - Does the current user (from
SecurityContext) have that role?
If yes → request proceeds to controller. If no → 403 Forbidden is returned.
◆ Stage 6: Controller Processes Request
The SecurityContext is accessible in the controller:
1@GetMapping("/users")2public List<User> getUsers() {3 Authentication auth = SecurityContextHolder.getContext().getAuthentication();4 String username = auth.getName(); // available here5 return userService.getAllUsers();6}10. Why Zero Code is Needed for Basic Form Login
Spring Boot's Default Security Configuration
Spring Boot ships with a pre-configured WebSecurityConfiguration class (SpringBootWebSecurityConfiguration) that automatically registers a SecurityFilterChain bean if you haven't defined your own.
This default bean includes:
1// From Spring Boot's SpringBootWebSecurityConfiguration (framework code — for illustration)2@Bean3SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {4 http5 .authorizeHttpRequests(requests -> requests.anyRequest().authenticated())6 .formLogin(withDefaults()) // ← form login enabled by default7 .httpBasic(withDefaults()); // ← basic auth also enabled by default8 return http.build();9}Because form login is the default, you get:
/loginpage (auto-generated)/logoutendpointUsernamePasswordAuthenticationFilterin the filter chain- Session creation on successful login
- Session validation on subsequent requests
All of this without writing a single line of security code.
11. Custom Security Filter Chain Configuration
When Do You Need a Custom Configuration?
- You want to relax authentication on specific (public) endpoints.
- You want a custom login/logout page instead of the default Spring-generated one.
- You want to restrict access by role (authorization).
- You want to switch to a different authentication method (e.g., JWT) — in which case you disable form login.
Writing a Custom `SecurityFilterChain`
1@Configuration2@EnableWebSecurity3public class SecurityConfig {4
5 @Bean6 public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {7 http8 .authorizeHttpRequests(auth -> auth9 .requestMatchers("/public/**").permitAll() // no auth required10 .anyRequest().authenticated() // everything else requires login11 )12 .formLogin(form -> form13 .loginPage("/my-custom-login") // custom login page URL14 .defaultSuccessUrl("/dashboard") // redirect after login15 .permitAll()16 )17 .logout(logout -> logout18 .logoutUrl("/my-logout") // custom logout URL19 .logoutSuccessUrl("/my-custom-login")20 .permitAll()21 );22
23 return http.build();24 }25}Using Defaults (Minimal Custom Config)
1@Bean2public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {3 http4 .authorizeHttpRequests(auth -> auth5 .requestMatchers("/users").permitAll() // public endpoint6 .anyRequest().authenticated()7 )8 .formLogin(Customizer.withDefaults()); // keep default login page and URLs9
10 return http.build();11}SecurityFilterChain bean disables the auto-configured default one. You now have full control. This is also where you'll later add .sessionManagement(), .csrf(), JWT filters, etc.12. Authorization Filter
What Is It?
The Authorization Filter (AuthorizationFilter in Spring Security 6+, formerly FilterSecurityInterceptor) sits at the end of the security filter chain and decides whether the authenticated user is permitted to access the requested resource.
Default Behavior
By default, Spring Security does not restrict which roles can access which endpoints. If a user is authenticated, they can access anything. Restrictions must be explicitly configured.
How to Add Role-Based Authorization in the Filter Chain
1@Bean2public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {3 http4 .authorizeHttpRequests(auth -> auth5 // Only users with ROLE_USER can access /users6 .requestMatchers("/users").hasRole("USER")7
8 // Users with either ROLE_USER or ROLE_ADMIN can access /products9 .requestMatchers("/products").hasAnyRole("USER", "ADMIN")10
11 // Admin-only endpoint12 .requestMatchers("/admin/**").hasRole("ADMIN")13
14 // Public endpoints15 .requestMatchers("/public/**").permitAll()16
17 // Everything else requires authentication (any role)18 .anyRequest().authenticated()19 )20 .formLogin(Customizer.withDefaults());21
22 return http.build();23}.hasRole("USER"), Spring Security automatically prepends ROLE_ to the string internally. So hasRole("USER") checks for the authority ROLE_USER. You do not need to write ROLE_USER yourself in the config — but the authority stored in the database or UserDetails must be ROLE_USER.What Happens During Authorization Filter Execution
- Request arrives at the Authorization Filter.
- The filter reads the
SecurityContextHolder— retrieves the authenticated user's roles. - It compares the user's roles against the required roles configured for the requested endpoint.
- If roles match → request proceeds to Dispatcher Servlet → Controller.
- If roles don't match →
403 Forbiddenis thrown.
Example: Role Mismatch
1# application.properties (for testing)2spring.security.user.roles=ADMIN1// SecurityConfig2.requestMatchers("/users").hasRole("USER")Result: User with ROLE_ADMIN tries to access /users (which requires ROLE_USER) → 403 Forbidden.
13. Two Phases of Authorization
Spring Security authorization can happen at two places in the request lifecycle:
Phase 1: Security Filter Level (Filter Chain)
Configured in SecurityFilterChain via .authorizeHttpRequests(). This is evaluated before the request reaches the controller. Applies URL-pattern-based rules.
1.requestMatchers("/admin/**").hasRole("ADMIN")Phase 2: Method Level (Controller / Service)
Evaluated after the request enters the controller or service. Uses annotations. This phase is common across all authentication methods (Form Login, JWT, OAuth, etc.) because it is independent of how the user authenticated.
1@PreAuthorize("hasRole('ADMIN')")2@GetMapping("/admin/dashboard")3public String adminDashboard() {4 return "Admin view";5}Enable method-level security with:
1@Configuration2@EnableMethodSecurity // enables @PreAuthorize, @PostAuthorize, @Secured3public class SecurityConfig { ... }Comparison
| Aspect | Filter-Level Authorization | Method-Level Authorization |
|---|---|---|
| Where | Security filter chain | Controller / Service |
| When | Before request reaches controller | Inside controller/service logic |
| Config | .authorizeHttpRequests() | @PreAuthorize, @Secured |
| Scope | URL-pattern based | Method based |
| Common to all auth methods? | No (each method has its own filter) | Yes — universal |
14. Session Management Controls
Controlling Maximum Sessions Per User
You can limit how many concurrent sessions a single user is allowed to have. This prevents a user from logging in from unlimited browsers or devices simultaneously.
1@Bean2public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {3 http4 .sessionManagement(session -> session5 .maximumSessions(1) // allow only 1 concurrent session per user6 .maxSessionsPreventsLogin(true) // prevent new login if max is reached7 )8 .formLogin(Customizer.withDefaults());9
10 return http.build();11}Behavior
maxSessionsPreventsLogin | Effect |
|---|---|
true | New login attempt is rejected if max sessions already exist. |
false (default) | New login succeeds; oldest session is invalidated (previous session kicked out). |
maximumSessions(2) or higher.15. Session Creation Policy
The session creation policy controls when Spring Security creates an HttpSession.
Configuration
1http2 .sessionManagement(session -> session3 .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) // default4 );Four Policy Values
| Policy | Behavior | Use Case |
|---|---|---|
IF_REQUIRED | Session created only when needed (e.g., for authenticated requests). Public endpoints do not get sessions. | Default — recommended for form login |
ALWAYS | A session is always created for every request, whether authentication is needed or not. Reuses existing sessions. | Rarely needed; causes unnecessary overhead |
NEVER | Spring Security never creates a session, but will use an existing one if already present. | Specific edge cases |
STATELESS | Spring Security never creates or uses a session. Every request must be fully self-authenticated. | JWT / OAuth / stateless APIs |
STATELESS. This tells Spring Security to never create or check HTTP sessions — all authentication happens via the token on each request.IF_REQUIRED is the default. You do not need to configure it explicitly for form login — it is already active. Public APIs do not generate sessions; only authenticated endpoints do.16. Disadvantages of Form Login Authentication
1. Vulnerable to CSRF (Cross-Site Request Forgery)
Since authentication is based on cookies carrying session IDs, a malicious website can trick a logged-in user's browser into making requests to your server — and the browser will automatically include the session cookie.
Spring Security's mitigation: CSRF protection is enabled by default for form login. Never disable it for stateful form-based apps.
1// DO NOT DO THIS for form login:2.csrf(csrf -> csrf.disable()) // ← dangerous for stateful auth2. Session Hijacking
The session ID travels in a cookie. If an attacker intercepts the cookie (e.g., on an unsecured HTTP connection), they can use it to impersonate the user.
Mitigations:
- Always use HTTPS.
- Use
HttpOnlyandSecurecookie flags. - Regenerate session ID after login.
3. Session Management Overhead
For complex business requirements, the framework's default session management may not be sufficient. In 2015–2016 era enterprise apps, teams manually managed custom session tables — tracking expiry, invalidation, and user-specific session behavior — which added significant development and operational overhead.
4. Scalability Issues in Distributed Systems
As discussed in Session Storage:
- In-memory sessions don't work across multiple server instances.
- Database-backed sessions (required for distributed deployments) add:
- Increased DB load — every request triggers a session lookup.
- Increased latency — DB round-trip on every authenticated request.
5. Database Load
With high traffic, every authenticated request involves a database query to validate the session. This can become a significant bottleneck at scale.
Common mitigations:
- Use Redis as a session store (faster than a relational DB).
- Use sticky sessions at the load balancer level (routes the same user to the same server — avoids DB lookup but reduces load balancer flexibility).
Summary of Disadvantages
| Disadvantage | Root Cause | Common Mitigation |
|---|---|---|
| CSRF vulnerability | Cookie-based session ID | Keep CSRF enabled; use SameSite cookies |
| Session hijacking | Session ID in cookie | HTTPS; HttpOnly + Secure flags |
| Session management overhead | Custom business needs require manual management | Use framework defaults; consider JWT |
| Distributed scalability | In-memory sessions not shared | DB or Redis session store |
| DB load / latency | Session lookup per request | Redis cache; JWT (no server-side state) |
17. Diagrams
Full Form Login Architecture Mind Map
State Diagram: Session Lifecycle
Security Filter Chain Sequence for Form Login
18. Key Observations
- Form login is the default Spring Boot Security authentication method — no configuration is required to use it.
- Two distinct flows exist: (1) Login flow — creates the session. (2) Resource access flow — validates the session.
UsernamePasswordAuthenticationFilterhandles only the login request. For all subsequent requests,SecurityContextHolderFilterhandles session validation.- No session is created during INSERT/POST of a regular resource. Sessions are created only during the login flow.
- The
Authenticationobject starts partial (created by the filter) and becomes fully populated (byDaoAuthenticationProvider) before being stored in theSecurityContext. - Session timeout is inactivity-based — each user request resets the countdown.
- CSRF protection is enabled by default for form login and should never be disabled for stateful apps.
- Authorization is separate from authentication — a user can be authenticated (
200) but unauthorized (403). - Role checks internally prepend
ROLE_—.hasRole("USER")checks forROLE_USERin theGrantedAuthoritylist. SessionCreationPolicy.STATELESSmust be used for JWT — it tells Spring Security never to create or use an HTTP session.
19. Common Mistakes
Mistake 1: Disabling CSRF for form-based login
1// ❌ Never do this for stateful form login2.csrf(csrf -> csrf.disable())CSRF attacks specifically exploit the cookie-based session mechanism. Disabling CSRF protection removes the main defense.
Fix: Keep CSRF enabled (it is the default). Only disable CSRF for fully stateless applications (JWT-based).
Mistake 2: Using in-memory sessions in a multi-instance deployment
1# ❌ No spring-session-jdbc — sessions stored in Tomcat memory only2# Users on Server 2 will not find sessions created on Server 1Fix: Add spring-session-jdbc (or Redis) and configure spring.session.store-type=jdbc.
Mistake 3: Confusing `hasRole("USER")` with `hasAuthority("USER")`
1// ❌ This will NOT match if stored authority is "ROLE_USER"2.hasAuthority("USER")3
4// ✅ Use hasRole — it automatically prepends "ROLE_"5.hasRole("USER") // checks for ROLE_USERMistake 4: Expecting the security filter chain to be written from scratch for form login
The default Spring Boot configuration handles form login automatically. You only need to write a custom SecurityFilterChain bean when you want to override or extend the defaults (custom login page, public endpoints, role restrictions, etc.).
Mistake 5: Confusing `401 Unauthorized` and `403 Forbidden`
| Status | Meaning | Cause in Spring Security |
|---|---|---|
401 Unauthorized | Not authenticated | Bad credentials, no session, expired session |
403 Forbidden | Authenticated but not authorized | User lacks the required role |
20. Best Practices
- Always use HTTPS to prevent session ID theft (session hijacking).
- Enable CSRF for all form-based (stateful) authentication. It is the default — do not disable it.
- Use database or Redis session storage in any multi-instance deployment.
- Set a reasonable session timeout based on your application's security requirements — not too long (security risk) and not too short (bad UX).
- Limit sessions per user with
.maximumSessions()to prevent session proliferation. - Use
SessionCreationPolicy.IF_REQUIRED(the default) so public APIs don't needlessly create sessions. - Define explicit roles and role restrictions — never rely on the "authenticated = can access everything" default in production.
- Use
SessionCreationPolicy.STATELESSonly for JWT — applying it to form login will break session-based authentication entirely. - Let Spring manage session tables via
spring.session.jdbc.initialize-schema=alwaysunless you have specific custom schema requirements. - Test your security configuration with Spring Security's test support (
MockMvc+@WithMockUser) before going to production.
21. Interview Notes
Commonly Asked Questions
Q: What is form login authentication and is it still relevant?
Form login is the traditional, stateful authentication method where a user submits credentials once, receives a session ID, and uses that session ID for subsequent requests. While JWT dominates modern REST APIs, form login is still used in server-rendered web applications and remains the default in Spring Boot Security. Understanding it is foundational to understanding why JWT was created.
Q: What is the default authentication method in Spring Boot Security?
Form login authentication. If no custom SecurityFilterChain is configured, Spring Boot defaults to form login (plus HTTP Basic). This is defined in SpringBootWebSecurityConfiguration in the framework.
Q: What is the difference between a session and a cookie?
- A session is a server-side object (
HttpSession) storing authentication state. - A cookie is a client-side mechanism used to transmit the session ID (
JSESSIONID) with each request. - The session lives on the server; the cookie is the key to look it up.
Q: How does Spring Boot Security handle session expiry?
Sessions are inactivity-based. The HttpSession has a maxInactiveInterval. Every time a request is made using a session, its lastAccessTime is updated and the expiry is recalculated as lastAccessTime + maxInactiveInterval. If no request is made for the duration of maxInactiveInterval, the session expires and the user must log in again.
Q: How do you limit a user to one active session at a time?
1http.sessionManagement(session -> session2 .maximumSessions(1)3 .maxSessionsPreventsLogin(true)4);Q: What is SessionCreationPolicy and what are its values?
It controls when Spring Security creates HTTP sessions:
IF_REQUIRED(default) — only when needed for authenticated requests.ALWAYS— always, even for public requests.NEVER— never creates, but uses existing if present.STATELESS— never creates or uses sessions (for JWT/OAuth).
Q: Why does form login break in a distributed system without a shared session store?
Because sessions are stored in the servlet container's memory (Tomcat). If a load balancer routes a user's request to a different instance than the one that created the session, that instance won't find the session and will redirect the user to login again. Solution: use spring-session-jdbc or spring-session-data-redis for a shared session store.
Q: What is CSRF and why is it a risk with form login?
CSRF (Cross-Site Request Forgery) exploits the browser's automatic cookie-sending behavior. A malicious site can make the user's browser send a request to your server, and the browser will automatically attach the session cookie — making the server think the request is legitimate. Spring Security's CSRF protection (enabled by default) prevents this by requiring a hidden CSRF token that the attacker's site cannot access.
Q: What are the two phases of authorization in Spring Security?
- Filter-level: via
.authorizeHttpRequests()inSecurityFilterChain— URL-pattern based, applied before the request reaches the controller. - Method-level: via
@PreAuthorize,@Securedon controller/service methods — applied inside the controller. This phase is authentication-method-agnostic.
22. Comparison Tables
Form Login vs JWT
| Feature | Form Login (Stateful) | JWT (Stateless) |
|---|---|---|
| Server stores state? | Yes (HttpSession) | No |
| What client sends | Session cookie | Bearer token in header |
| Session timeout | Server-side, configurable | Token expiry in payload |
| Multi-server support | Requires shared session store | No shared store needed |
| Logout | Invalidate server session | Client discards token (complex server-side) |
| CSRF risk | High (cookie auto-sent) | Lower (token in header, not cookie) |
| Default in Spring Boot | Yes | No (must configure) |
| When to use | Server-rendered web apps | REST APIs, SPAs, mobile apps |
Session Creation Policy Comparison
| Policy | Creates Session | Uses Existing | Best For |
|---|---|---|---|
IF_REQUIRED | Only when needed | Yes | Form login (default) |
ALWAYS | Always | Yes | Rarely needed |
NEVER | Never | Yes | Edge cases |
STATELESS | Never | Never | JWT, OAuth |
23. Practice Questions
Easy
- What is the default authentication method in Spring Boot Security?
- What are the default login and logout URLs provided by Spring Boot for form login?
- What is the difference between a session and a cookie?
- What does
server.servlet.session.timeout=5mconfigure? - Which Spring Security filter handles the login form submission?
Medium
- Trace the complete flow of a POST
/loginrequest from the client through every Spring Security component to the point the session is stored. - Trace the complete flow of a subsequent GET
/usersrequest (with a valid session cookie) through the security filter chain. - Why does form login break in a distributed system with multiple server instances, and how do you fix it?
- What is the role of
HttpSessionSecurityContextRepository? - Explain the difference between a
401 Unauthorizedand a403 Forbiddenresponse in Spring Security.
Hard
- A user logs in successfully (session created in DB), then immediately calls
/adminand receives a403. Authentication logs showisAuthenticated = true. What is the most likely cause, and how do you fix it? - Explain the inactivity-based session expiry mechanism. How does Spring update the
EXPIRY_TIMEcolumn in theSPRING_SESSIONtable on each request? - Your application runs on 4 instances behind a load balancer. Customers report being logged out randomly. You are using
spring-session-jdbc. What could still cause this, and how would you investigate? - Design a
SecurityFilterChainconfiguration that: (a) allows/public/without authentication, (b) restricts/admin/toROLE_ADMIN, (c) restricts/users/**to eitherROLE_USERorROLE_ADMIN, (d) limits each user to 2 concurrent sessions, (e) uses default login/logout pages. - A security audit flags that your form-login app has CSRF disabled. The developer argues "it's fine, we validate the
Originheader manually." Explain why this is insufficient and what CSRF token-based protection adds.
24. Summary
Revision Bullets
- Form login is the default Spring Boot Security authentication method — no code needed to activate it.
- Stateful — server creates and maintains an
HttpSessionafter successful login; client sends only the session ID cookie on subsequent requests. - Two flows: (1) Login → creates session. (2) Resource access → validates session.
UsernamePasswordAuthenticationFilterhandles the login POST.SecurityContextHolderFilterhandles session validation for all other requests.DaoAuthenticationProviderperforms the actual authentication: hashes the incoming password, loads stored user, compares, returns fully authenticatedAuthenticationobject.HttpSessionSecurityContextRepositorycreates theHttpSession, stores theSecurityContextinside it, and saves it to memory or DB.- Session ID sent to client in
Set-Cookie: JSESSIONIDheader. - Session timeout is inactivity-based — default 30 minutes (Tomcat). Configurable via
server.servlet.session.timeout. - Multi-instance deployments require
spring-session-jdbcor Redis so all instances share the same session store. - CSRF is enabled by default for form login — never disable it for stateful applications.
- Authorization filter checks user roles (from
SecurityContext) against endpoint-required roles (fromSecurityFilterChainconfig). Mismatch =403 Forbidden. .hasRole("USER")automatically checks forROLE_USERauthority.- Two phases of authorization: filter-level (URL patterns) and method-level (
@PreAuthorize) — method-level is universal across all auth methods. maximumSessions(1)limits concurrent sessions per user.SessionCreationPolicy.STATELESSis for JWT — never use for form login.- Disadvantages: CSRF risk, session hijacking, session management overhead, DB load, scalability challenges in distributed systems.
- These disadvantages directly motivated the creation of JWT and OAuth.
Study guide generated from the "Concept and Coding" Spring Boot Security lecture series — Form Login Authentication.
Mastery check
How well can you recall this?
Finished this lesson?