Stateless authentication lets a server check who you are without saving your info between requests. This makes apps faster and easier to scale.
Stateless authentication mental model in Spring Boot
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Spring Boot
1. Client sends login info to server. 2. Server verifies and creates a token (like JWT). 3. Server sends token back to client. 4. Client sends token with each request in headers. 5. Server checks token to allow or deny access.
The token usually contains user info and expiry time.
Server does not keep any session data; it trusts the token.
Examples
Spring Boot
POST /login
Request Body: {"username": "user", "password": "pass"}
Response: {"token": "eyJhbGciOiJI..."}Spring Boot
GET /profile
Headers: Authorization: Bearer eyJhbGciOiJI...
Response: {"name": "User", "email": "user@example.com"}Sample Program
This simple Spring Boot app shows stateless auth. The login returns a token string. The profile endpoint checks the token in the Authorization header. No session is stored on the server.
Spring Boot
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.*; import jakarta.servlet.http.HttpServletRequest; @SpringBootApplication @RestController public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } // Simulate login endpoint @PostMapping("/login") public String login(@RequestParam String username, @RequestParam String password) { if ("user".equals(username) && "pass".equals(password)) { // In real app, create JWT token here return "token12345"; // simple token for demo } return "Invalid credentials"; } // Protected endpoint @GetMapping("/profile") public String profile(HttpServletRequest request) { String authHeader = request.getHeader("Authorization"); if (authHeader != null && authHeader.equals("Bearer token12345")) { return "{\"name\": \"User\", \"email\": \"user@example.com\"}"; } return "Unauthorized"; } }
Important Notes
Tokens should be signed and encrypted in real apps for security.
Tokens usually expire after some time to reduce risk.
Always send tokens over HTTPS to keep them safe.
Summary
Stateless authentication uses tokens to identify users without server memory.
Clients send tokens with each request to prove who they are.
This method helps apps scale and stay simple.
Practice
1. What is the main idea behind stateless authentication in Spring Boot?
easy
Solution
Step 1: Understand stateless authentication concept
Stateless means the server does not save any user session data between requests.Step 2: Identify how user identity is maintained
Clients send a token with each request to prove who they are without server memory.Final Answer:
The server does not keep user session data; clients send tokens each time. -> Option AQuick Check:
Stateless = No server session, token sent each time [OK]
Hint: Stateless means no server memory, token sent every request [OK]
Common Mistakes:
- Thinking server stores session data
- Confusing cookies with stateless tokens
- Assuming login required every request
2. Which of the following is the correct way to send a token in a stateless Spring Boot API request?
easy
Solution
Step 1: Recall token transmission best practice
Tokens are usually sent in the Authorization header using the Bearer scheme.Step 2: Eliminate incorrect methods
Request body is not standard for tokens; server-side session breaks statelessness; URL query parameters are insecure and not recommended.Final Answer:
Send the token in the Authorization header as a Bearer token. -> Option BQuick Check:
Token in Authorization header = correct [OK]
Hint: Tokens go in Authorization header as Bearer [OK]
Common Mistakes:
- Putting token in request body
- Using server session storage
- Sending token in URL query insecurely
3. Given this Spring Boot controller snippet using stateless authentication:
What will be the response if the client sends header
@GetMapping("/profile")
public ResponseEntity<String> getProfile(@RequestHeader("Authorization") String authHeader) {
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
return ResponseEntity.status(401).body("Unauthorized");
}
String token = authHeader.substring(7);
if (token.equals("valid-token")) {
return ResponseEntity.ok("User Profile Data");
} else {
return ResponseEntity.status(403).body("Forbidden");
}
}What will be the response if the client sends header
Authorization: Bearer valid-token?medium
Solution
Step 1: Check Authorization header presence and format
The header is present and starts with "Bearer ", so it passes the first check.Step 2: Extract token and compare
The token extracted is "valid-token", which matches the expected valid token.Step 3: Determine response
Since token is valid, the method returns 200 OK with "User Profile Data".Final Answer:
200 OK with 'User Profile Data' -> Option CQuick Check:
Valid token = 200 OK response [OK]
Hint: Valid Bearer token returns 200 OK [OK]
Common Mistakes:
- Confusing 401 and 403 status codes
- Ignoring token prefix check
- Assuming server stores session
4. Identify the bug in this stateless authentication filter code snippet:
What is the main issue?
public boolean isValidToken(String token) {
if (token == null || token.isEmpty()) {
return false;
}
// Token validation logic
return token.equals("valid-token");
}
public void doFilter(HttpServletRequest req, HttpServletResponse res) {
String auth = req.getHeader("Authorization");
if (auth != null && auth.startsWith("Bearer ")) {
String token = auth.substring(7);
if (!isValidToken(token)) {
res.setStatus(401);
}
}
// Continue filter chain
}What is the main issue?
medium
Solution
Step 1: Analyze header usage
The original code calls auth.startsWith("Bearer ") without checking if auth is null.Step 2: Identify risk
If Authorization header is missing, auth is null, so calling startsWith causes NullPointerException.Final Answer:
Possible NullPointerException if Authorization header is missing -> Option AQuick Check:
Check null before startsWith to avoid error [OK]
Hint: Check for null before calling startsWith [OK]
Common Mistakes:
- Assuming header always present
- Mixing 401 and 403 status codes
- Ignoring null safety in Java
5. In a stateless Spring Boot app using JWT tokens, which approach best supports scaling across multiple servers?
hard
Solution
Step 1: Understand stateless scaling needs
Scaling means any server can handle any request without shared session state.Step 2: Evaluate options
Storing sessions in DB or memory adds state and complexity; sticky sessions tie users to one server, limiting scaling.Step 3: Identify best stateless method
Validating JWT tokens on each request keeps servers stateless and allows easy scaling.Final Answer:
Validate JWT tokens on each request without server session storage. -> Option DQuick Check:
Stateless + JWT = validate token each request [OK]
Hint: Stateless scaling means no server session, validate tokens each time [OK]
Common Mistakes:
- Using sticky sessions limits scaling
- Storing sessions breaks statelessness
- Caching sessions in memory causes sync issues
