Spring Security
Form Login and HTTP Basic Authentication
Configuring default logins templates and API basic authentication headers.
Introduction
Spring Security supports two primary traditional authentication mechanisms out of the box: HTTP Basic Authentication and Form Login. While both mechanisms verify user identity, they operate differently in terms of protocol flow, state management, and use cases.
Why It Matters
Choosing the wrong authentication strategy can compromise either security or user experience. HTTP Basic Auth is simple and stateless but offers poor session management and is vulnerable if not forced over HTTPS. Form Login provides a rich, user-friendly interactive login experience with session management but requires cookies, session storage, and protections against Cross-Site Request Forgery (CSRF).
Real-World Analogy
Think of HTTP Basic Authentication like carrying a physical security badge that you must swipe at every single door inside a building. If you lose the badge, or if someone copies it, they can access anything immediately since no state is saved at the doors. Think of Form Login like showing your passport at the entrance desk to receive a wristband (Session Cookie). You only show your credentials once. Inside the building, you just show your wristband, which the security guards can revoke or cut at any time if they suspect suspicious behavior.
Detailed Mechanics
1. HTTP Basic Authentication Flow
When a client requests a protected resource without authentication:
- The server replies with HTTP status
401 Unauthorizedand includes aWWW-Authenticate: Basic realm="RealmName"header. - The browser catches this header and prompts the user with a native username/password dialog box.
- The browser base64-encodes the credentials as
username:passwordand sends them in theAuthorizationheader:Authorization: Basic dXNlcjpwYXNzd29yZA==. - On the server side,
BasicAuthenticationFilterextracts the header, decodes the credentials, and passes them to theAuthenticationManager.
2. Form Login Flow
When a user visits a protected URL in their browser:
- The server detects lack of authentication and redirects the browser (HTTP
302 Found) to a login page (default/login). - The user submits a POST request to
/loginwith form parametersusernameandpassword. UsernamePasswordAuthenticationFilterintercepts the POST request, extracts the fields, and builds aUsernamePasswordAuthenticationToken.- After successful authentication, the server generates a session, returns a cookie (
JSESSIONID) to the browser, and redirects the user back to the originally requested page.
Comparison Table
| Feature | HTTP Basic Authentication | Form Login |
|---|---|---|
| User Interface | Browser-native popup window (non-customizable) | Customizable HTML form template |
| State / Session | Typically stateless (credentials sent on every request) | Stateful (uses HTTP Session via JSESSIONID cookies) |
| Logout Support | Difficult (browser caches credentials until close) | Easy (invalidates the session on the server) |
| Target Use Case | Simple system APIs, microservices, testing | User-facing web applications |
Practical Example
The following configuration class configures both mechanisms, exposing public paths while protecting general API endpoints under basic auth and user flows under form login:
Quick Quiz
Q1: Why is HTTP Basic Authentication considered insecure for internet usage unless combined with HTTPS?
A) It does not require a username.
B) The credentials are sent in plain text equivalent (Base64 encoding), which can easily be intercepted and decoded by anyone sniffing network traffic.
C) It consumes too much CPU power on the server.
D) It uses session cookies that never expire.
Answer: B — Base64 is NOT encryption; it is trivial to decode. Transport Layer Security (HTTPS) is mandatory to encrypt the headers.
Q2: Which filter intercepts standard form logins submitted via HTTP POST requests?
A) BasicAuthenticationFilter
B) UsernamePasswordAuthenticationFilter
C) SecurityContextPersistenceFilter
D) DefaultLoginPageGeneratingFilter
Answer: B — UsernamePasswordAuthenticationFilter is responsible for processing POST-based form logins.
Scenario-Based Challenge
Production Scenario:
You configure a Spring Boot backend API to support both formLogin() and httpBasic(). Your React frontend makes API requests from another domain using HTTP Basic Authentication. However, unauthenticated requests are returning a 302 Found redirect to /custom-login instead of a 401 Unauthorized response. What is causing this, and how do you resolve it?
This occurs because when both filters are configured, the default exception entry point redirected to is specified by formLogin(), which directs unauthorized requests to the login HTML page (using a 302 redirect).
To resolve this for REST API endpoints:
- Configure separate security filter chains using
@Orderannotations. Set the first chain to target/api/**paths and configure onlyhttpBasic(). - In the API security chain, register an explicit
AuthenticationEntryPointthat writes an HTTP 401 response direct to the socket instead of redirecting.
Interview Questions
1. Conceptual: How can you disable session creation in Spring Security for a completely stateless REST API?
Configure session creation policy as stateless in the security chain setup:
http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)). This prevents Spring Security from creating or using the HttpSession to store security contexts.
2. Concept: What is the risk of using HTTP Basic Authentication inside a browser client?
Browsers cache HTTP Basic credentials internally and send them automatically on every subsequent request to the target domain. There is no simple way for the client application to trigger a logout, because the browser refuses to clear its credential cache unless the application restarts or the user manually clears history.
Production Considerations
If utilizing Form Login in production, ensure you implement CSRF (Cross-Site Request Forgery) protection (which is enabled by default in Spring Security). For REST APIs where clients store authorization states (like JWTs or access tokens) inside memory instead of session cookies, CSRF protection can be safely disabled, but remember to enforce strict CORS rules and short-lived tokens.