Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 39 ยท Getting Started

Core Concepts: Authentication, SecurityContext and Authorities

Learn the types every Spring Security feature builds on: Authentication, GrantedAuthority, SecurityContext, SecurityContextHolder, and how the context travels between threads.

Spring Security looks huge, but a handful of types appear in every feature. Once you can name them and say what each one holds, the rest of the framework becomes a set of variations. This lesson introduces those types and rebuilds them in plain Java so you can see how they behave, including the one behavior that surprises almost everyone: what happens to the logged-in user when your code starts another thread.

The vocabulary

Type Meaning
Authentication A request to authenticate, and (after success) the result: who the caller is
Principal The identity inside the Authentication (often a UserDetails or a name)
Credentials The proof: a password or token. Erased after authentication
GrantedAuthority One permission, role or scope, as a string such as ROLE_ADMIN
SecurityContext Holds the current Authentication
SecurityContextHolder Gives static access to the SecurityContext of the current thread
AuthenticationManager Takes an unauthenticated Authentication and returns an authenticated one

The shape of the interface is worth reading once:

Java
public interface Authentication extends Principal, Serializable {
    Collection<? extends GrantedAuthority> getAuthorities();
    Object getCredentials();
    Object getDetails();
    Object getPrincipal();
    boolean isAuthenticated();
    void setAuthenticated(boolean isAuthenticated);
}

An Authentication has two lives. Before checking it is a token with credentials: "I claim to be ana, and here is her password". After a successful check the same kind of object comes back with the credentials cleared, isAuthenticated() true and the authorities filled in. A common implementation is UsernamePasswordAuthenticationToken, which has two constructors: one for the unauthenticated request (new UsernamePasswordAuthenticationToken(name, password)) and one for the authenticated result (new UsernamePasswordAuthenticationToken(principal, null, authorities)).

flowchart LR
  A["Unauthenticated token<br/>name + password"] --> B["AuthenticationManager"]
  B --> C["Authenticated token<br/>principal + authorities<br/>credentials erased"]
  C --> D["SecurityContext"]
  D --> E["SecurityContextHolder"]

The same concept, before and after the check, ending up in the holder.

GrantedAuthority: roles and permissions as strings

A GrantedAuthority is a thin wrapper around one string, usually through SimpleGrantedAuthority("ROLE_ADMIN"). Spring does not distinguish "roles" from "permissions" at this level: a role is just an authority whose name starts with ROLE_. The helper hasRole("ADMIN") adds that prefix for you, whereas hasAuthority("ROLE_ADMIN") does not. Roles and authorities goes deep on this; for now remember that everything is a string in a collection.

SecurityContextHolder

The place your own code usually touches security is the holder:

Java
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
boolean admin = auth.getAuthorities().stream()
    .anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"));

In a controller you rarely need the static call. Spring MVC can inject the information for you:

Java
@GetMapping("/me")
String me(Authentication authentication, Principal principal,
          @AuthenticationPrincipal UserDetails user) {
    return user.getUsername();
}

Inside the framework the holder works like a ThreadLocal by default. A servlet container handles one request on one thread from start to finish, so storing the context in a ThreadLocal means "the current user" is available everywhere in that request without passing it around. After the request, SecurityContextHolderFilter clears it so the pooled thread does not leak the identity to the next caller.

Holder strategies and threads

The strategy is configurable:

  • MODE_THREADLOCAL (default): each thread has its own context.
  • MODE_INHERITABLETHREADLOCAL: a new child thread copies the parent's context at creation time.
  • MODE_GLOBAL: one context for the whole JVM (only for desktop applications).

This is the surprise: if a controller starts new Thread(...), uses CompletableFuture.supplyAsync, or calls an @Async method on a normal executor, the worker thread sees no authentication under the default strategy. The next example makes that visible with a stand-in holder you can read in full.

Java A ThreadLocal security context and a child thread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The inheritable mode looks like a fix, but it is a trap with thread pools: a pooled thread is created once, so it copies the context of whichever request created it and keeps it for later tasks. The correct tools are the ones Spring provides: DelegatingSecurityContextExecutor and DelegatingSecurityContextRunnable copy the context into the task when you submit it, and with @EnableAsync the support is added for you when you use Spring's task executor with security integration. In short: propagate on submit, clear on completion.

The lifecycle of one request

Putting the types together for one login-protected request:

  1. A filter extracts credentials and builds an unauthenticated Authentication.
  2. It passes it to the AuthenticationManager.
  3. The manager returns an authenticated Authentication (with authorities) or throws AuthenticationException.
  4. The filter stores it in a new SecurityContext and sets it on the holder.
  5. Later, authorization code reads the Authentication from the holder and decides.
  6. At the end of the request the holder is cleared, and for session-based logins the context is saved to the HttpSession.

The final point matters: with sessions, the next request is authenticated by loading the saved context from the session, with no password check at all. With tokens there is no session, so each request authenticates again from the token.

Building and clearing a context yourself

You will sometimes need to run code as a certain user, for example in a scheduled job or an integration test. The recommended way is to create a fresh empty context rather than mutating the shared one:

Java
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(new UsernamePasswordAuthenticationToken(
        "batch-job", null, AuthorityUtils.createAuthorityList("ROLE_SYSTEM")));
SecurityContextHolder.setContext(context);
try {
    service.runNightlyJob();
} finally {
    SecurityContextHolder.clearContext();
}

Always clear in a finally block. Forgetting this on a pooled thread leaves a privileged identity behind for whoever uses the thread next.

The final stand-in shows the full cycle (credential token, manager, authenticated token with the password erased) with the same structure Spring uses.

Java Unauthenticated token in, authenticated token out

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does an Authentication object contain after a successful login?

    The result holds who the caller is and what they have, with the password cleared so it does not linger in memory.
  2. 2. A controller starts new Thread(...) and that thread calls SecurityContextHolder.getContext().getAuthentication(). With the default strategy, what does it get?

    The default holder is a plain ThreadLocal, so other threads have their own empty context.
  3. 3. Why is MODE_INHERITABLETHREADLOCAL dangerous with a thread pool?

    Inheritance happens at thread creation, not per task. Use the delegating executors to propagate per task.
  4. 4. How is ROLE_ADMIN related to a GrantedAuthority?

    Spring models roles as authorities with a conventional ROLE_ prefix.

Summary

  • Authentication is both the request to authenticate and its result; the result has authorities and erased credentials.
  • A GrantedAuthority is a string; a role is an authority starting with ROLE_.
  • SecurityContextHolder stores the context in a ThreadLocal and is cleared at the end of each request.
  • Other threads do not see the user unless you propagate the context with the delegating executors.
  • Session-based requests restore the context from the session; token-based requests authenticate every time.

Next: Boot auto-configuration and defaults