Authentication, JWT and Password Hashing
50 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Security questions come up in almost every Spring Boot interview: how login works, why passwords are hashed, what is inside a JWT, and why an API answers 401 or 403. The interviewer checks that you can walk through ShopLite's login end to end and name the usual mistakes.
Authentication vs authorisation; 401 vs 403
Authentication answers "who are you?" (a password or a token proves it). Authorisation answers "what may you do?" (roles or ownership). Authentication comes first: no identity gives 401, an identity without permission gives 403.
Every request answers two questions in this order. This example decides 401, 403 or 200 for three different callers.
Example 1 · 401 or 403: the two questions for every request
import java.util.Map;import java.util.Set;
/** A tiny model of the two questions Spring Security asks for every request. Lab code only. */public class AccessCheckDemo {
// Valid tokens and the roles of their users (in ShopLite the signed JWT carries the roles) static final Map<String, Set<String>> TOKENS = Map.of( "token-asha", Set.of("CUSTOMER"), "token-admin", Set.of("ADMIN"));
static int check(String path, String token) { if (path.startsWith("/api/v1/products")) { return 200; } if (token == null || !TOKENS.containsKey(token)) { return 401; // authentication failed: who are you? } if (path.startsWith("/api/v1/admin") && !TOKENS.get(token).contains("ADMIN")) { return 403; // authorisation failed: known, but not allowed } return 200; }
public static void main(String[] args) { String[][] requests = { { "/api/v1/products", null }, { "/api/v1/orders", null }, { "/api/v1/orders", "token-forged" }, { "/api/v1/orders", "token-asha" }, { "/api/v1/admin/users", "token-asha" }, { "/api/v1/admin/users", "token-admin" } }; for (String[] r : requests) { String who = r[1] == null ? "(no token)" : r[1]; System.out.printf("%-20s %-13s -> %d%n", r[0], who, check(r[0], r[1])); } }}/api/v1/products (no token) -> 200 /api/v1/orders (no token) -> 401 /api/v1/orders token-forged -> 401 /api/v1/orders token-asha -> 200 /api/v1/admin/users token-asha -> 403 /api/v1/admin/users token-admin -> 200
What this code does
- No token or an unknown token stops at the first question, so the answer is 401. Asha's valid token passes it, but she is not an admin, so the admin page gives 403.
- Spring Security asks the same two questions in its filter chain:
BearerTokenAuthenticationFilterfor "who?" andAuthorizationFilterfor "allowed?".
A wrong password, a missing token or an expired token gives 401. A valid token with the wrong role, or another customer's order, gives 403 (or 404 to hide that it exists). In Spring Security the AuthenticationEntryPoint writes the 401 and the AccessDeniedHandler the 403.
Revise: Authentication vs authorisation (opens in a new tab), Roles vs authorities (opens in a new tab), Security error responses (opens in a new tab).
Predict the output
Allowed, 401 or 403?
Read the rule and the caller, then pick the result.
Round 1 of 3
What happens to the caller?
Hashing, encryption and encoding
Hashing turns a password into a fixed fingerprint that cannot be reversed. Encryption can be reversed by anyone with the key, and encoding such as Base64 by anyone at all. Passwords are hashed, never encrypted.
The app never needs the original password back; it only checks a typed one. If a database and its key leak together, encrypted passwords leak too, while hashes must be guessed one try at a time.
One-line answer: "A hash is one-way, encryption is two-way with a key, and encoding is only a different format."
Revise: Hashing, encryption and encoding (opens in a new tab).
Predict the output
Encode or hash?
Predict what each program prints.
Round 1 of 2
What does this program print?
Salt and BCrypt
A salt is a random value stored next to each password hash and mixed in before hashing. Equal passwords then get different hashes, and precomputed rainbow tables become useless. BCrypt creates the salt for you.
Two users with the same password must not get the same hash. The first example adds a salt by hand; the second uses Spring's BCrypt.
Example 2 · Why every password gets its own salt
import java.nio.charset.StandardCharsets;import java.security.MessageDigest;import java.util.HexFormat;
/** Why every password gets its own salt. Lab code: real apps use BCrypt, which salts for you and is slow on purpose. */public class SaltDemo {
static String sha256(String text) throws Exception { byte[] digest = MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8)); return HexFormat.of().formatHex(digest); }
static String shortHash(String hash) { return hash.substring(0, 16) + "..."; }
public static void main(String[] args) throws Exception { String ashaPassword = "college@123"; String raviPassword = "college@123"; // same password, different student
System.out.println("Without a salt:"); System.out.println(" asha " + shortHash(sha256(ashaPassword))); System.out.println(" ravi " + shortHash(sha256(raviPassword)) + " <- same hash gives the secret away");
String ashaSalt = "Q7xp"; // real salts: 16 random bytes per user String raviSalt = "m2Kd"; String ashaStored = sha256(ashaSalt + ashaPassword); String raviStored = sha256(raviSalt + raviPassword); System.out.println("With a salt per user:"); System.out.println(" asha " + ashaSalt + " " + shortHash(ashaStored)); System.out.println(" ravi " + raviSalt + " " + shortHash(raviStored) + " <- different hashes");
// Login: hash the typed password with the stored salt again, then compare System.out.println("Login with college@123: " + ashaStored.equals(sha256(ashaSalt + "college@123"))); System.out.println("Login with College@123: " + ashaStored.equals(sha256(ashaSalt + "College@123"))); }}Without a salt: asha 0b8005b3478b4b6d... ravi 0b8005b3478b4b6d... <- same hash gives the secret away With a salt per user: asha Q7xp 13bbbaf86457e9bd... ravi m2Kd ef9e0150754d6ca9... <- different hashes Login with college@123: true Login with College@123: false
What this code does
- Without a salt, Asha and Ravi get the same hash, so cracking one password cracks both, and a rainbow table can look it up. With a salt each, the hashes differ.
- Login re-hashes the typed password with the stored salt and compares. SHA-256 is far too fast for real passwords; this only shows the salt idea that BCrypt builds in.
Example 3 · BCrypt in Spring: encode twice, check with matches
Runs in: a small Maven project with spring-security-crypto (version from Spring Boot 4.1.1)
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;
public class BcryptInterviewDemo {
public static void main(String[] args) { PasswordEncoder encoder = new BCryptPasswordEncoder(); // cost 10 by default String password = "hostel-room-214";
// Sign-up: store only the hash String first = encoder.encode(password); String second = encoder.encode(password); System.out.println("hash 1: " + first); System.out.println("hash 2: " + second); System.out.println("same text? " + first.equals(second));
// Login: matches() reads the salt and cost from the stored hash and hashes the typed password again System.out.println("matches(right, hash 1) = " + encoder.matches(password, first)); System.out.println("matches(right, hash 2) = " + encoder.matches(password, second)); System.out.println("matches(wrong, hash 1) = " + encoder.matches("hostel-room-215", first)); }}hash 1: $2a$10$FIcC2oFx/z5rUvFdo9t1iuDKZyiUeKWL9wyUe6PcY51VaDC7BsTUK hash 2: $2a$10$piFXZ2rk3wyzAxbX1iqZL.YqBdyjhccwO8g4KHXjd7xFyk3FEx9U. same text? false matches(right, hash 1) = true matches(right, hash 2) = true matches(wrong, hash 1) = false
What this code does
- Each
encodepicks a new random salt, so the two stored values differ, yetmatchesaccepts the right password for both: the salt and cost are read back from the stored value. - Your hashes will differ on every run. This is the interview answer to "how do you check a password if the hash is different every time?"
BCrypt is slow on purpose: its cost factor (10 by default, meaning 2^10 rounds) makes every guess expensive, while SHA-256 lets an attacker try billions of guesses per second. A stored value such as $2a$10$... holds the version, cost, salt and hash (60 characters), so matches(raw, stored) can re-hash and compare; never use equals. BCrypt uses at most 72 bytes, and createDelegatingPasswordEncoder() stores {bcrypt}... so the algorithm can change later. Argon2 is the modern alternative.
Predict the output
Do the hashes match?
Both users choose the password college@123.
Round 1 of 2
What does this program print?
JWT structure, signing and the stateless login flow
A JWT (JSON Web Token) is header.payload.signature, each part Base64URL-encoded. The payload holds claims such as sub, roles and exp. The signature proves the token was not changed; it does not hide anything.
A token is issued once at login and checked on every request. This example signs a token by hand, then checks it, including a forged edit.
Example 4 · Issue and check an HS256 token by hand
import java.nio.charset.StandardCharsets;import java.security.MessageDigest;import java.util.Base64;import java.util.regex.Matcher;import java.util.regex.Pattern;
import javax.crypto.Mac;import javax.crypto.spec.SecretKeySpec;
/** Issue and check an HS256 token by hand. Lab code: ShopLite uses Spring Security's NimbusJwtEncoder/Decoder. */public class JwtFlowDemo {
static final byte[] KEY = "lab-key-for-hs256-demo-32-bytes!".getBytes(StandardCharsets.UTF_8); static final Base64.Encoder ENC = Base64.getUrlEncoder().withoutPadding();
static String b64(String json) { return ENC.encodeToString(json.getBytes(StandardCharsets.UTF_8)); }
static String hmac(String data) throws Exception { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(KEY, "HmacSHA256")); return ENC.encodeToString(mac.doFinal(data.getBytes(StandardCharsets.UTF_8))); }
/** Login succeeded: sign a short-lived token with the user id and roles only. */ static String issue(long userId, String role, long now, long ttlSeconds) throws Exception { String header = b64("{\"alg\":\"HS256\",\"typ\":\"JWT\"}"); String payload = b64("{\"sub\":\"" + userId + "\",\"roles\":[\"" + role + "\"],\"iat\":" + now + ",\"exp\":" + (now + ttlSeconds) + "}"); return header + "." + payload + "." + hmac(header + "." + payload); }
/** Every request: check the signature first, then the expiry. */ static String check(String token, long now) throws Exception { String[] parts = token.split("\\."); if (parts.length != 3) { return "401 malformed"; } byte[] expected = hmac(parts[0] + "." + parts[1]).getBytes(StandardCharsets.US_ASCII); if (!MessageDigest.isEqual(expected, parts[2].getBytes(StandardCharsets.US_ASCII))) { return "401 bad signature"; } String payload = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8); Matcher exp = Pattern.compile("\"exp\":(\\d+)").matcher(payload); if (!exp.find() || now >= Long.parseLong(exp.group(1))) { return "401 expired"; } return "200 OK for " + payload; }
public static void main(String[] args) throws Exception { long loginTime = 1_792_137_489L; // fixed "now" so the output never changes String token = issue(2, "CUSTOMER", loginTime, 900); // 15-minute access token System.out.println("Token: " + token);
System.out.println("After 1 minute: " + check(token, loginTime + 60)); System.out.println("After 16 minutes: " + check(token, loginTime + 960));
// Change the role in the payload but keep the old signature String[] p = token.split("\\."); String forgedPayload = b64("{\"sub\":\"2\",\"roles\":[\"ADMIN\"],\"iat\":1792137489,\"exp\":1792138389}"); System.out.println("Forged ADMIN: " + check(p[0] + "." + forgedPayload + "." + p[2], loginTime + 60)); }}Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIyIiwicm9sZXMiOlsiQ1VTVE9NRVIiXSwiaWF0IjoxNzkyMTM3NDg5LCJleHAiOjE3OTIxMzgzODl9.rP9YXJKhVMhlIrKAJMcoJ3q95L3ntGW4uLnQEG2oPEk
After 1 minute: 200 OK for {"sub":"2","roles":["CUSTOMER"],"iat":1792137489,"exp":1792138389}
After 16 minutes: 401 expired
Forged ADMIN: 401 bad signatureWhat this code does
issueis what the login endpoint does after the password check;checkis what theJwtDecoderdoes on every request: signature first, then expiry.- Changing
CUSTOMERtoADMINwithout the key leaves a signature that no longer matches, so the forged token gets 401. After 16 minutes the 15-minute token has expired.
HS256 uses one shared secret to sign and verify, which suits one API that checks its own tokens, like ShopLite. RS256 signs with a private key and verifies with a public key, so many services can verify tokens that only the auth server can create. ShopLite issues a 15-minute HS256 token and expects Authorization: Bearer <token>.
Revise: JWT structure (opens in a new tab), Validating a JWT on each request (opens in a new tab).
Order of execution
The JWT login flow
Put the steps of a stateless login in order.
The Spring Security filter chain
Security runs before your controller. The output below lists the filters in order, then a request with no token gets 401 and a customer on an admin URL gets 403.
Example 5 · SecurityConfig for a stateless JWT API
Runs in: the shoplite-api Spring Boot project (Section 17)
package com.shoplite.common.security;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.HttpMethod;import org.springframework.security.config.Customizer;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.http.SessionCreationPolicy;import org.springframework.security.crypto.factory.PasswordEncoderFactories;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;import org.springframework.security.web.SecurityFilterChain;
/** The interview version of ShopLite's security setup (Section 17). JwtEncoder/JwtDecoder beans live in JwtConfig. */@Configurationpublic class SecurityConfig {
@Bean SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http // 1. CORS first: browser preflights are answered before any token check .cors(Customizer.withDefaults()) // 2. URL rules, checked top to bottom: the first match decides .authorizeHttpRequests(auth -> auth .requestMatchers(HttpMethod.POST, "/api/v1/auth/login", "/api/v1/auth/register").permitAll() .requestMatchers(HttpMethod.GET, "/api/v1/products/**").permitAll() .requestMatchers("/api/v1/admin/**").hasRole("ADMIN") .anyRequest().authenticated()) .oauth2ResourceServer(oauth -> oauth.jwt(jwt -> jwt.jwtAuthenticationConverter(rolesFromToken()))) // 3. Token in a header, no cookie, no session: CSRF is off and every request proves itself .csrf(csrf -> csrf.disable()) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); return http.build(); }
/** The "roles" claim (["ADMIN"]) becomes the authority ROLE_ADMIN, which hasRole("ADMIN") checks. */ private static JwtAuthenticationConverter rolesFromToken() { JwtGrantedAuthoritiesConverter roles = new JwtGrantedAuthoritiesConverter(); roles.setAuthoritiesClaimName("roles"); roles.setAuthorityPrefix("ROLE_"); JwtAuthenticationConverter converter = new JwtAuthenticationConverter(); converter.setJwtGrantedAuthoritiesConverter(roles); return converter; }
/** Stores "{bcrypt}$2a$10$...": the {id} prefix lets the algorithm change later. */ @Bean PasswordEncoder passwordEncoder() { return PasswordEncoderFactories.createDelegatingPasswordEncoder(); }}Startup log with logging.level.org.springframework.security=DEBUG:
... DEBUG ... o.s.s.web.DefaultSecurityFilterChain : Will secure any request with filters: DisableEncodeUrlFilter, WebAsyncManagerIntegrationFilter, SecurityContextHolderFilter, HeaderWriterFilter, CorsFilter, LogoutFilter, OAuth2ProtectedResourceMetadataFilter, BearerTokenAuthenticationFilter, RequestCacheAwareFilter, SecurityContextHolderAwareRequestFilter, AnonymousAuthenticationFilter, SessionManagementFilter, ExceptionTranslationFilter, AuthorizationFilter
$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/api/v1/admin/users
401
$ curl -s -o /dev/null -w "%{http_code}\n" -H "Authorization: Bearer $ASHA_TOKEN" http://localhost:8080/api/v1/admin/users
403What this code does
- The startup log lists the filter chain in order:
CorsFilterearly, thenBearerTokenAuthenticationFilter, andExceptionTranslationFilterjust beforeAuthorizationFilter. There is noCsrfFilter, because CSRF is disabled. - No token gives 401; Asha's customer token on an admin URL gives 403. Interviewers often ask you to explain each part of this setup.
Spring Security is a chain of servlet filters before the DispatcherServlet: CorsFilter answers preflights, BearerTokenAuthenticationFilter checks the token, ExceptionTranslationFilter turns security exceptions into 401 or 403, and AuthorizationFilter applies your requestMatchers. You configure it with a SecurityFilterChain bean. Read the current user with @AuthenticationPrincipal or SecurityContextHolder.
Revise: The security filter chain (opens in a new tab), SecurityFilterChain configuration (opens in a new tab).
CSRF and CORS
CSRF tricks a signed-in browser into sending a request with its cookies. CORS is the browser asking a server whether a page from another origin may read its responses. CORS protects users in browsers; it is not access control.
Two browser questions that are often mixed up: CSRF abuses cookies, and CORS limits which pages may read a response.
A stateless API that reads the token only from the Authorization header may disable CSRF, because a forged cross-site request cannot add that header; keep it for session-cookie logins. A preflight is an OPTIONS request the browser sends first, and the server answers with Access-Control-Allow-Origin and the allowed methods. List exact origins, never * together with cookies; curl ignores CORS.
Revise: CSRF protection (opens in a new tab), CORS preflight requests (opens in a new tab).
JWT traps: secrets in the payload, no expiry
A refresh token is a long-lived token, tracked on the server, that the client exchanges for a new short-lived access token. Revoking it ends the session, which is how logout works with stateless JWTs.
The two most asked traps are secrets in the payload and a token that never expires. This example decodes a token with no key and accepts one with no exp.
Example 6 · Two JWT traps: a readable payload and a token that never expires
import java.nio.charset.StandardCharsets;import java.util.Base64;
/** Two classic JWT mistakes, shown without any key at all. Lab code only. */public class JwtTrapsDemo {
static String payloadOf(String token) { return new String(Base64.getUrlDecoder().decode(token.split("\\.")[1]), StandardCharsets.UTF_8); }
/** BROKEN: only rejects a token whose exp has passed, so a token with no exp never expires. */ static boolean naiveNotExpired(String payload, long now) { int i = payload.indexOf("\"exp\":"); return i < 0 || now < Long.parseLong(payload.substring(i + 6).replaceAll("\\D.*", "")); }
/** FIXED: exp is required. */ static boolean strictNotExpired(String payload, long now) { int i = payload.indexOf("\"exp\":"); return i >= 0 && now < Long.parseLong(payload.substring(i + 6).replaceAll("\\D.*", "")); }
public static void main(String[] args) { // Trap 1: secrets in the payload. Base64URL is encoding, not encryption. String careless = "eyJhbGciOiJIUzI1NiJ9" + ".eyJzdWIiOiJhc2hhQGNvbGxlZ2UuaW4iLCJwYXNzd29yZCI6ImNvbGxlZ2VAMTIzIiwidXBpUGluIjoiNDQyMSJ9" + ".c2lnbmF0dXJl"; System.out.println("Anyone can read: " + payloadOf(careless));
// Trap 2: a token issued with no exp claim String forever = "{\"sub\":\"2\",\"roles\":[\"CUSTOMER\"]}"; String normal = "{\"sub\":\"2\",\"roles\":[\"CUSTOMER\"],\"exp\":1792138389}"; long aYearLater = 1_823_673_489L; System.out.println("No exp, naive check, a year later: " + naiveNotExpired(forever, aYearLater)); System.out.println("No exp, strict check, a year later: " + strictNotExpired(forever, aYearLater)); System.out.println("With exp, strict check, a year later: " + strictNotExpired(normal, aYearLater)); }}Anyone can read: {"sub":"asha@college.in","password":"college@123","upiPin":"4421"}
No exp, naive check, a year later: true
No exp, strict check, a year later: false
With exp, strict check, a year later: falseWhat this code does
- The first token was never decrypted, only decoded: no key was needed to read the password and UPI PIN. That is why the payload holds ids and roles only.
- The naive check treats a missing
expas "not expired", so that token is still accepted a year later. The strict check requiresexp.
Keep only ids and roles in the payload. Use short access tokens (5 to 15 minutes) plus a refresh token; logout means deleting the refresh token or keeping a small denylist of token ids (jti). Reject alg: none, keep the HS256 key (at least 32 bytes) in the environment and never in Git, and use HTTPS. localStorage is readable by injected script; an HttpOnly cookie is not, but then CSRF returns.
Revise: Expiry and signing keys (opens in a new tab), Refresh tokens and logout (opens in a new tab), Where clients store tokens (opens in a new tab).
Find the bug
Spot the JWT mistake
One line in each snippet is a security mistake. Click it.
Anyone who sees this token can read a secret. Which line?
Round 1 of 3Next step
Check your understanding
12 quick questions