Why this matters
- Stateless APIs scale horizontally — no session store to replicate across BookStore pods.
- OAuth2 is the industry standard for third-party login (Google, GitHub) and service-to-service auth.
- JWT structure (header, payload, signature) is a frequent interview topic for backend roles.
Stateless JWT APIs
L1 · FresherClients send Authorization: Bearer <token>; BookStore validates signature and expiry without server-side sessions.
OAuth2 resource server
L2 · IntermediateSpring Security OAuth2 Resource Server validates JWTs from an issuer (Keycloak, Cognito) using JWK sets.
Claims and authorities
L3 · AdvancedMap scope or roles claims to GrantedAuthority for @PreAuthorize expressions.
Token refresh vs opaque tokens
L4 · ExpertSPA flows use refresh tokens carefully; BFF pattern hides tokens from browsers. Know trade-offs for mobile BookStore apps.
JWT structure
A JSON Web Token has three Base64-encoded parts separated by dots:
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyQGV4YW1wbGUuY29tIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
JWT parts
- Header — Algorithm (
HS256,RS256) and token type (JWT). - Payload — Claims:
sub(subject/user),exp(expiry),roles, custom fields. - Signature — HMAC or RSA signature proving the token was issued by a trusted authority.
Never put sensitive data (passwords, credit cards) in the payload — it is only encoded, not encrypted.
Issuing tokens on login
// learn:fragment
@Service
public class AuthService {
private final UserRepository userRepository;
private final PasswordEncoder encoder;
private final JwtService jwtService;
public AuthResponse login(LoginRequest request) {
User user = userRepository.findByEmail(request.email())
.orElseThrow(() -> new BadCredentialsException("Invalid credentials"));
if (!encoder.matches(request.password(), user.getPasswordHash())) {
throw new BadCredentialsException("Invalid credentials");
}
String token = jwtService.generateToken(user);
return new AuthResponse(token, "Bearer", 3600);
}
}
// learn:fragment
@Service
public class JwtService {
@Value("${bookstore.jwt.secret}")
private String secret;
@Value("${bookstore.jwt.expiration-seconds:3600}")
private long expiration;
public String generateToken(User user) {
return Jwts.builder()
.subject(user.getEmail())
.claim("roles", user.getRole())
.issuedAt(new Date())
.expiration(new Date(System.currentTimeMillis() + expiration * 1000))
.signWith(Keys.hmacShaKeyFor(secret.getBytes()))
.compact();
}
public Claims parseToken(String token) {
return Jwts.parser()
.verifyWith(Keys.hmacShaKeyFor(secret.getBytes()))
.build()
.parseSignedClaims(token)
.getPayload();
}
}
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 5 sections
- Validating tokens in the filter chain
- OAuth2 resource server
- OAuth2 login for the admin site
- Client usage
- Token refresh
Test yourself
Answer these before moving on — recall is what makes it stick.