Practice: HTTP Basic, sessions and CSRF
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Four habits cause most sign-in bugs in this module. Each one has a short, reliable fix.
Mistake 1: treating a Basic header as safe to share
The first example decodes three headers that developers pasted into a support ticket "to help debugging". Each one hands out a working login.
Example 1 · Headers pasted into a support ticket
import java.nio.charset.StandardCharsets;import java.util.Base64;import java.util.List;
public class TicketHeaderDemo {
/** Returns what a Basic header gives away, or a note when the header is not Basic. */ static String reveal(String header) { if (!header.startsWith("Basic ")) { return header.split(" ")[0] + " header: no password inside"; } String pair = new String(Base64.getDecoder().decode(header.substring(6)), StandardCharsets.UTF_8); int colon = pair.indexOf(':'); return "user " + pair.substring(0, colon) + ", password " + pair.substring(colon + 1); }
public static void main(String[] args) { // Headers pasted by developers into a support ticket "to help debugging" List<String> pasted = List.of( "Basic b3JkZXItc2VydmljZTpzM2NyZXQtZnJvbS1lbnY=", "Basic cmF2aS5rdW1hckBleGFtcGxlLmNvbTpTaG9wQDRwbQ==", "Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.c2lnbmF0dXJl"); for (String header : pasted) { System.out.println(reveal(header)); } System.out.println("Every Basic line above is a working password. Rotate both now."); }}user order-service, password s3cret-from-env user ravi.kumar@example.com, password Shop@4pm Bearer header: no password inside Every Basic line above is a working password. Rotate both now.
What this code does
- Two of the three headers decode straight into a user name and password with one library call; no key is involved.
- The bearer token contains no password, but it is still a working credential until it expires, so it must not be pasted either.
The fix has two parts. Never print or log Authorization (mask it, as the HTTP Basic practice did), and when a header has leaked, rotate the secret: set a new password or service secret, because Basic has no other way to cut access.
Mistake 2: session cookie flags left at their defaults
Default cookie flags are not production flags. Tomcat sets HttpOnly, but Secure is off and no SameSite value is sent unless you configure it.
server.servlet.session.timeout=15mserver.servlet.session.cookie.http-only=trueserver.servlet.session.cookie.secure=trueserver.servlet.session.cookie.same-site=lax- Write all four lines in the main
application.properties, so a forgotten profile does not make the cookie weaker. SameSite=Noneis not "safe and flexible": it sends the cookie on every cross-site request, and browsers reject it without Secure.- Choose the timeout for the app: minutes for an admin or bank app, longer only when the risk is small.
A plain JSESSIONID=...; Path=/ can travel over HTTP and goes with every cross-site request in browsers that do not default to Lax.
Mistake 3: csrf.disable() copied into a cookie-based app
csrf.disable() is correct only for header-based APIs. The second example shows a cookie-only POST, exactly what another site can make a browser send, succeeding.
Example 2 · A forged POST with CSRF disabled and with it on
Runs in: the session-lab practice project (Spring Boot 4.1)
// session-lab SecurityConfig with the copied line.formLogin(Customizer.withDefaults()).logout(Customizer.withDefaults()).csrf(csrf -> csrf.disable()); // copied from a token API tutorial: WRONG here(session-lab with .csrf(csrf -> csrf.disable()) added; jar.txt holds a signed-in admin session)
$ curl -i -b jar.txt -X POST http://localhost:8080/admin/products/8/deactivate
HTTP/1.1 200
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Content-Length: 62
Date: Fri, 16 Oct 2026 07:56:01 GMT
{"id":8,"isActive":false,"changedBy":"admin@shoplite.example"}
(the same request with the default configuration, CSRF on)
$ curl -i -b jar.txt -X POST http://localhost:8080/admin/products/8/deactivate
HTTP/1.1 403
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 07:20:26 GMT
{"timestamp":"2026-10-16T07:20:26.438Z","status":403,"error":"Forbidden","path":"/admin/products/8/deactivate"}What this code does
- With CSRF off, a request with only the session cookie and no token deactivates product 8: any website could make an admin's browser send it.
- With the default configuration the same request is stopped with 403 before the controller runs.
Tutorials for token APIs always contain the line, and copying it into an app that signs in with a session cookie removes the one check that stops forged requests.
The fix is to delete the line and let the default protection work: forms rendered with th:action or Spring's own pages already carry the token, and JavaScript apps use csrf.spa(). Do not "fix" 403 errors by disabling CSRF; find which request is missing its token.
Mistake 4: picking a sign-in style before asking who the client is
The client decides the sign-in style, not habit. Ask three questions: is the caller a person or a program, does a browser send the credentials automatically, and how many servers answer the requests?
Program calling a service over HTTPS -> Basic with a random secret (or a token)Person, server-rendered pages, few servers -> form login + session cookie + CSRF onPerson, mobile app or SPA, many servers -> short-lived token in Authorization, STATELESSSPA that must keep a session cookie -> session + csrf.spa()- Using sessions for a three-copy API means sticky sessions or a shared store from day one.
- Using Basic for customers means their real password sits in the app and travels with every call.
- Using long-lived tokens because "logout is hard" makes theft worse; keep them short and revoke refresh tokens.
Finish up
Mark complete & continue
Next: Mini project: session login for an admin console