liveBook · Manning

SecurityContextHolder

As explained in Spring Security in Action, Second Edition

SecurityContextHolder is the Spring Security holder that associates a security context with the current execution thread or other configured scope.

SecurityContextHolder manages access to the SecurityContext, which stores the authenticated entity’s Authentication after successful authentication. In a thread-per-request application, each request commonly receives its own context. section 6.2 section 6.2.1

Choose the strategy according to how execution is organized:

  • MODE_THREADLOCAL keeps context details isolated per thread and suits independent web requests. section 6.2
  • MODE_INHERITABLETHREADLOCAL copies context details to framework-created asynchronous threads, such as those used by @Async. section 6.2.2
  • MODE_GLOBAL shares one context across application threads, fitting some standalone applications but requiring concurrency care. section 6.2.3

Reading the authenticated user

An endpoint can call SecurityContextHolder.getContext(), obtain Authentication, and return its name. Spring can instead inject Authentication directly into the endpoint parameter. An @Async method requires an inheritable strategy; application-created threads require explicit context copying. section 6.2.1 section 6.2.2

How Spring Security in Action, Second Edition covers it

How deep it goes
Explains context storage, three strategies, endpoint access, asynchronous propagation, and concurrency limits without detailing internal implementation.
Examples
Uses /hello endpoint access, Authentication parameter injection, @Async execution, and strategy configuration through InitializingBean.
What you can do after
Diagnose/debug with it by locating missing authentication across request, asynchronous, and application-created threads.
How it connects
Connects SecurityContextHolder to SecurityContext, Authentication, application threads, asynchronous methods, and Spring configuration.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Security in Action, Second Edition. The section links point to the parts of the book it draws on.