Skip to lesson

SecurityContext and the current user

A customer opens "my orders". The server must know who is asking without trusting a customer id typed by the client. Where does that identity live while the request is handled?

SecurityContextHolder, SecurityContext and Authentication

SecurityContextHolder is a class with static methods that gives you the current SecurityContext, which holds one Authentication: the caller.

Read the current caller straight from SecurityContextHolder in a lab endpoint, and call it as two different users.

Example 1 · Reading the SecurityContext directly

Runs in: the security-lab practice project (Spring Boot 4.1)

Java
// src/main/java/com/shoplite/lab/me/WhoAmIController.java (the /context endpoint)@RestController@RequestMapping("/api/v1/me")class WhoAmIController {
    record ContextView(String authenticationType, String name, String principalType,                       Object credentials, List<String> authorities, boolean authenticated) {    }
    /** Way 1: read the context directly from the holder. */    @GetMapping("/context")    ContextView context() {        SecurityContext context = SecurityContextHolder.getContext();        Authentication auth = context.getAuthentication();        return new ContextView(                auth.getClass().getSimpleName(),                auth.getName(),                auth.getPrincipal().getClass().getSimpleName(),                auth.getCredentials(),                names(auth.getAuthorities()),                auth.isAuthenticated());    }
    private static List<String> names(Collection<? extends GrantedAuthority> authorities) {        return authorities.stream().map(GrantedAuthority::getAuthority).sorted().toList();    }}
Sample output
$ curl -u asha:asha-pass-1 http://localhost:8080/api/v1/me/context
{"authenticationType":"UsernamePasswordAuthenticationToken","name":"asha","principalType":"User","credentials":null,"authorities":["FACTOR_PASSWORD","ROLE_CUSTOMER"],"authenticated":true}
$ curl -u admin:admin-pass-1 http://localhost:8080/api/v1/me/context
{"authenticationType":"UsernamePasswordAuthenticationToken","name":"admin","principalType":"User","credentials":null,"authorities":["FACTOR_PASSWORD","ROLE_ADMIN"],"authenticated":true}

What this code does

  • SecurityContextHolder.getContext() returns this request's context; getAuthentication() is what BasicAuthenticationFilter stored after checking the password.
  • The type is UsernamePasswordAuthenticationToken, the principal is Spring's User and credentials is null because the password was erased.
  • The same endpoint returns a different person for each caller: identity comes from the credentials, not from the URL.

SecurityContextHolder.getContext().getAuthentication() works anywhere in code that runs for the request. The filters fill it in order: SecurityContextHolderFilter starts each request with an empty context, BasicAuthenticationFilter stores the authenticated user after a good password, and AnonymousAuthenticationFilter stores anonymousUser when nobody signed in. At the end of the request the context is cleared.

Why does this matter? The identity comes from a checked password (later a signed token), never from data the client typed into a form. A customer cannot become someone else by changing a customerId field, because the server does not ask the client who it is.

Examples 1, 2 and 5 run in the security-lab project: Example 2's chain from the previous lesson, with the lab users asha (CUSTOMER) and admin (ADMIN).

Principal, credentials and authorities

Principal is the user inside an Authentication. After a username and password sign-in it is a UserDetails object, and getName() returns its username.

An Authentication has three parts: the principal, the credentials and the authorities. These calls show each one for the signed-in user asha.

Java
Authentication auth = SecurityContextHolder.getContext().getAuthentication();auth.getName();          // "asha"auth.getPrincipal();     // the User (UserDetails) objectauth.getCredentials();   // null after sign-in: the password is erasedauth.getAuthorities();   // [FACTOR_PASSWORD, ROLE_CUSTOMER]auth.isAuthenticated();  // true

The credentials are the proof, such as the password. After a successful sign-in they are null, because Spring erases the password so it is not kept in memory. The authorities are what the user may do, as strings: roles appear with the ROLE_ prefix, such as ROLE_CUSTOMER. Spring Security 7 also adds a FACTOR_PASSWORD authority, which records how the user signed in; you can ignore it for now.

What can go wrong: code that checks authorities.contains("ADMIN") never matches, because the stored string is ROLE_ADMIN. The Roles and permissions module uses hasRole("ADMIN"), which adds the prefix for you.

Predict the output

Read the Authentication

asha has just signed in with curl -u asha:asha-pass-1.

Round 1 of 3

What does this print?

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
System.out.println(auth.getName());

The current user in a controller: @AuthenticationPrincipal or Authentication

@AuthenticationPrincipal on a controller parameter asks Spring MVC to pass in the principal of the current Authentication, typed as you need it.

Add two endpoints that let Spring pass in the principal and the whole Authentication as parameters.

Example 2 · @AuthenticationPrincipal and an Authentication parameter

Runs in: the security-lab practice project (Spring Boot 4.1)

Java
// src/main/java/com/shoplite/lab/me/WhoAmIController.java (two more endpoints)record Me(String username, List<String> authorities) {}
/** Way 2: let Spring pass the principal (the UserDetails) as a parameter. */@GetMappingMe me(@AuthenticationPrincipal UserDetails user) {    return new Me(user.getUsername(), names(user.getAuthorities()));}
/** Way 3: let Spring pass the whole Authentication as a parameter. */@GetMapping("/auth")Me fromAuthentication(Authentication authentication) {    return new Me(authentication.getName(), names(authentication.getAuthorities()));}
Sample output
$ curl -u asha:asha-pass-1 http://localhost:8080/api/v1/me
{"username":"asha","authorities":["ROLE_CUSTOMER"]}
$ curl -u admin:admin-pass-1 http://localhost:8080/api/v1/me/auth
{"username":"admin","authorities":["FACTOR_PASSWORD","ROLE_ADMIN"]}
$ curl -i http://localhost:8080/api/v1/me
HTTP/1.1 401
WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
...
Content-Length: 0

What this code does

  • Spring MVC fills both parameters from the security context; the methods never touch SecurityContextHolder.
  • UserDetails.getAuthorities() lists only the user's role; the Authentication also carries FACTOR_PASSWORD, added by Spring Security 7 at sign-in.
  • A guest never reaches the method: the chain answers 401 first.

A parameter of type Authentication gives you the whole object. Both are cleaner than calling SecurityContextHolder yourself: the method shows in its signature that it needs the user, and a test can pass one in. They differ in detail: user.getAuthorities() returns the user's own roles (ROLE_CUSTOMER); authentication.getAuthorities() returns what this sign-in granted, which in Spring Security 7 also contains FACTOR_PASSWORD.

These endpoints sit behind anyRequest().authenticated(), so an anonymous caller gets 401 before the method runs. If you ever make such an endpoint public, @AuthenticationPrincipal UserDetails user is null for guests, because anonymousUser is not a UserDetails. ShopLite's real /api/v1/me/... endpoints arrive in the Roles and permissions module, using the user id from the token.

Services receive the user id as a parameter

Passing the user id as a parameter means the controller reads the current user once and gives the service a plain value, such as orderService.ordersOf(customerId).

Compare a service that reads the hidden context with one that takes the customer id as a parameter, then run both in a nightly job.

Example 3 · Hidden context vs a customer id parameter

CurrentUserDesignDemo.javaJava
import java.util.List;import java.util.Map;
/** Stands in for SecurityContextHolder: set only while a web request is being handled. */class RequestContext {    static final ThreadLocal<Long> CUSTOMER_ID = new ThreadLocal<>();}
record OrderSummary(long id, long customerId, String status) {}
/** Style A: the service reads "who is calling" from the context itself. */class ContextReadingOrderService {    private final List<OrderSummary> orders;
    ContextReadingOrderService(List<OrderSummary> orders) {        this.orders = orders;    }
    List<OrderSummary> myOrders() {        Long customerId = RequestContext.CUSTOMER_ID.get();   // hidden input        return orders.stream().filter(o -> o.customerId() == customerId).toList();    }}
/** Style B: the caller passes the customer id; the service has no hidden input. */class OrderService {    private final List<OrderSummary> orders;
    OrderService(List<OrderSummary> orders) {        this.orders = orders;    }
    List<OrderSummary> ordersOf(long customerId) {        return orders.stream().filter(o -> o.customerId() == customerId).toList();    }}
public class CurrentUserDesignDemo {
    public static void main(String[] args) {        List<OrderSummary> orders = List.of(                new OrderSummary(2, 2, "DELIVERED"), new OrderSummary(7, 2, "DELIVERED"),                new OrderSummary(14, 2, "SHIPPED"), new OrderSummary(16, 7, "PLACED"));
        OrderService service = new OrderService(orders);        System.out.println("Customer 2: " + service.ordersOf(2).stream().map(OrderSummary::id).toList());
        Map<Long, String> report = Map.of(7L, service.ordersOf(7).get(0).status());        System.out.println("Nightly report: " + report);
        // Style A works only inside a request; in a job the context is empty.        ContextReadingOrderService hidden = new ContextReadingOrderService(orders);        try {            System.out.println(hidden.myOrders());        } catch (NullPointerException e) {            System.out.println("Style A in a nightly job: NullPointerException (no current user)");        }    }}
Output
Customer 2: [2, 7, 14]
Nightly report: {7=PLACED}
Style A in a nightly job: NullPointerException (no current user)

What this code does

  • OrderService.ordersOf(long customerId) works the same from a controller, a nightly job or a test: every input is visible.
  • ContextReadingOrderService.myOrders() reads a thread-local that only a web request sets; in the job it is null and unboxing it throws.
  • In ShopLite the controller takes the id from the authenticated user and passes it down; the body never decides whose data is used.

The service stays a normal Java class with all of its inputs in its parameters. It is also called from places with no web request: a nightly report, a message listener, a unit test. There the security context is empty, so a service that reads it hides an input that suddenly is missing. With a parameter, the test simply passes 2L.

The rule for ShopLite: controllers translate HTTP and security into plain values, services work with ids. The id always comes from the authenticated user, never from the request body, so customers cannot ask for someone else's orders.

Find the bug

Find the hidden input

Each snippet works in a browser test and breaks somewhere else. Click the risky line.

This service fails in a nightly job and in a unit test.

Round 1 of 2

Thread-local storage: the context belongs to the request thread

A ThreadLocal is a variable that has a separate value for each thread.

See one value per thread in plain Java, then a new thread started inside a controller that cannot see the caller.

Example 4 · ThreadLocal: one value per thread, and why it must be cleared

ThreadLocalContextDemo.javaJava
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;
/** A tiny copy of the idea behind SecurityContextHolder: one value per thread. */class CurrentUser {    private static final ThreadLocal<String> HOLDER = new ThreadLocal<>();
    static void set(String username) { HOLDER.set(username); }    static String get() { return HOLDER.get(); }    static void clear() { HOLDER.remove(); }}
public class ThreadLocalContextDemo {
    static void handleRequest(String signedInUser, boolean clearAtEnd) {        if (signedInUser != null) {            CurrentUser.set(signedInUser);        }        try {            System.out.println(Thread.currentThread().getName() + " sees user: " + CurrentUser.get());        } finally {            if (clearAtEnd) {                CurrentUser.clear();            }        }    }
    public static void main(String[] args) throws Exception {        // 1. Each thread has its own value        CurrentUser.set("asha");        Thread other = new Thread(() -> System.out.println("new thread sees user: " + CurrentUser.get()));        other.start();        other.join();        System.out.println("main thread sees user: " + CurrentUser.get());        CurrentUser.clear();
        // 2. A server reuses threads: forget to clear and the next request sees the old user        ExecutorService pool = Executors.newSingleThreadExecutor(r -> new Thread(r, "worker-1"));        System.out.println("-- without clear --");        pool.submit(() -> handleRequest("asha", false)).get();        pool.submit(() -> handleRequest(null, false)).get();     // a guest request on the same thread        pool.submit(CurrentUser::clear).get();        System.out.println("-- with clear --");        pool.submit(() -> handleRequest("asha", true)).get();        pool.submit(() -> handleRequest(null, true)).get();        pool.shutdown();        pool.awaitTermination(5, TimeUnit.SECONDS);    }}
Output
new thread sees user: null
main thread sees user: asha
-- without clear --
worker-1 sees user: asha
worker-1 sees user: asha
-- with clear --
worker-1 sees user: asha
worker-1 sees user: null

What this code does

  • The new thread sees null although main set asha: each thread has its own value.
  • With a reused thread and no clear(), the guest request sees asha: a user leak between requests. With clear() in finally, the guest sees null.
  • SecurityContextHolderFilter does exactly this set-then-clear for every request, so your code never has to.

Example 5 · A new thread in a controller, and DelegatingSecurityContextRunnable

Runs in: the security-lab practice project (Spring Boot 4.1)

Java
// src/main/java/com/shoplite/lab/me/WhoAmIController.java (thread endpoints)record ThreadView(String requestUser, String newThreadUser) {}
/** The context is stored per thread: a thread you start yourself does not see it. */@GetMapping("/thread")ThreadView thread() throws InterruptedException {    String requestUser = SecurityContextHolder.getContext().getAuthentication().getName();    AtomicReference<String> seen = new AtomicReference<>();    Thread worker = new Thread(() -> {                // a new thread, as a careless "send email later" would start        Authentication auth = SecurityContextHolder.getContext().getAuthentication();        seen.set(auth == null ? "null (no authentication)" : auth.getName());    });    worker.start();    worker.join();    return new ThreadView(requestUser, seen.get());}
/** The fix: wrap the task so it carries the caller's security context into the new thread. */@GetMapping("/thread-fixed")ThreadView threadFixed() throws InterruptedException {    String requestUser = SecurityContextHolder.getContext().getAuthentication().getName();    AtomicReference<String> seen = new AtomicReference<>();    Runnable task = () -> seen.set(SecurityContextHolder.getContext().getAuthentication().getName());    Thread worker = new Thread(new DelegatingSecurityContextRunnable(task));    worker.start();    worker.join();    return new ThreadView(requestUser, seen.get());}
Sample output
$ curl -u asha:asha-pass-1 http://localhost:8080/api/v1/me/thread
{"requestUser":"asha","newThreadUser":"null (no authentication)"}
$ curl -u asha:asha-pass-1 http://localhost:8080/api/v1/me/thread-fixed
{"requestUser":"asha","newThreadUser":"asha"}

What this code does

  • The request thread knows asha; the thread started inside the method has no authentication at all.
  • DelegatingSecurityContextRunnable copies the current context into the task and clears it when the task ends, so the worker sees asha.
  • For background work, passing the customer id to the task is usually simpler and clearer than copying the context.

SecurityContextHolder uses a thread-local by default (MODE_THREADLOCAL). Tomcat handles each request on one thread, so "the context of this thread" means "the context of this request". Two things follow. A thread you start yourself does not see the caller: inside it, getAuthentication() is null. And because Tomcat reuses threads, the context must be cleared after every request, or the next caller on that thread would inherit the previous user; SecurityContextHolderFilter does that clearing for you.

When work must continue on another thread with the same user, wrap the task: new DelegatingSecurityContextRunnable(task) copies the context in and clears it afterwards; DelegatingSecurityContextExecutorService does the same for a whole thread pool. Better still, pass the user id as a parameter, as in the previous section.

Next step

Check your understanding

11 quick questions