Chapter 6: Implementing authentications
Introduces where authentication decisions happen in Spring Security and what follows when a request is accepted or rejected.
After this chapter you will be able to
- Authentication Decision Responsibilities. Explain how an authentication request reaches the AuthenticationProvider and what that provider decides.
- Authentication Outcomes and Context. Distinguish what happens when a request is not authenticated from what happens when it is authenticated.
- Custom authentication with AuthenticationProvider. Explain why an enterprise application might need authentication beyond username and password and how Spring Security accommodates custom authentication logic.
- Authentication request representation. Explain that Authentication represents an authentication request and holds details of the entity requesting access, called the principal. Describe how it extends Java Security’s Principal interface, aiding compatibility with other implementations.
- Authentication method meanings. Describe what isAuthenticated(), getCredentials(), and getAuthorities() return in this section’s account of the Authentication contract.
- Authentication method outcomes. Describe what authenticate() receives and what it should do on success, failure, or an unsupported request. Explain why a successful result is normally stripped of sensitive data such as the password.
- Provider support and delegation. Explain how supports() helps an authentication manager choose among providers, and distinguish recognition of an Authentication type from a provider's later decision to handle or reject a particular request.
- Custom credential verification flow. Trace how the example authenticates a username-and-password request, including what happens when the user is missing, the password is wrong, or the password matches.
- Custom provider registration. Describe how the example makes its custom AuthenticationProvider available to Spring and plugs it into the security configuration.
- Authenticated Details in Security Context. Explain that after successful authentication, the security context stores the Authentication object for the rest of the request, making details such as the current user's username and authorities available.
- Security Context Holding Strategies. Distinguish the three SecurityContextHolder strategies by whether the context belongs to each thread, is inherited by a new asynchronous thread, or is shared across all application threads.
- Thread-local security context isolation. Explain that Spring Security’s default MODE_THREADLOCAL strategy gives each request thread access to its own security context in a traditional servlet application. Describe why a newly created thread does not receive the original thread’s context details.
- Accessing the authenticated entity. Describe how code can obtain the SecurityContext through SecurityContextHolder.getContext() after authentication and then obtain its Authentication object. Explain that Spring can instead inject Authentication directly into an endpoint method parameter.
- Asynchronous security context gap. Explain why an @Async method may find Authentication null when the default security-context strategy is used.
- Inheritable context propagation limits. Describe how MODE_INHERITABLETHREADLOCAL addresses the asynchronous-thread problem, how the section says to select it, and when it does not suffice.
- Global context suitability. Explain that MODE_GLOBAL shares one security context across application threads and may suit a standalone application, but not a web server handling independent requests.
- Security context in self-managed threads. Explain why a task run on a self-managed thread cannot assume it has the request thread’s security context, using the section’s Callable example.
- Security context task decorators. Describe how the delegating task wrappers propagate the current security context, and distinguish which wrapper to use for a task with a return value.
- ExecutorService security context propagation. Explain how DelegatingSecurityContextExecutorService propagates the security context when an application submits a task to an ExecutorService, and distinguish this from decorating each task.
- HTTP Basic suitability. Explain why the book has used HTTP Basic for examples and why it may not fit every real-world scenario.
- HTTP Basic realm configuration. Explain how an HTTP Basic realm name is configured and where it appears in the response.
- Custom failed-authentication response. Describe how to customize an HTTP Basic failure response with an AuthenticationEntryPoint and why its contents require care.
- Form login configuration and defaults. Explain how to enable form-based login and what Spring Security provides with the minimal configuration.
- Successful login destinations. Explain the normal redirect after login and the two customization options introduced here.
What it builds on
- Implementing filters in the Spring Security architecture (chapter 5) · The HTTP filter layer handles incoming requests.
- Detailing on the GrantedAuthority contract (chapter 3) · The concept of granted authorities.
- Understanding the UserDetailsService contract (chapter 3) · The UserDetailsService contract used for user lookup.
- The PasswordEncoder contract (chapter 4) · The PasswordEncoder contract used for passwords.
Section by section
Introduction
Introduces where authentication decisions happen in Spring Security and what follows when a request is accepted or rejected.
- Authentication Decision Responsibilities: Explain how an authentication request reaches the AuthenticationProvider and what that provider decides.
Why it matters: It separates the component that passes along the request from the one that decides whether to authenticate it. - Authentication Outcomes and Context: Distinguish what happens when a request is not authenticated from what happens when it is authenticated.
Why it matters: The outcome determines whether the request stops or has authenticated details available for authorization.
Key terms: AuthenticationProvider, AuthenticationManager, HTTP filter layer, HTTP 401 Unauthorized, authorization, SecurityContext
6.1 Understanding the AuthenticationProvider
Explains why applications may need authentication methods beyond username and password and identifies AuthenticationProvider as Spring Security’s way to define custom authentication logic.
- Custom authentication with AuthenticationProvider: Explain why an enterprise application might need authentication beyond username and password and how Spring Security accommodates custom authentication logic.
Why it matters: This explains why an application might use an AuthenticationProvider rather than rely on a provided authentication implementation.
Key terms: AuthenticationProvider, custom authentication logic
6.1.1 Representing the request during authentication
This section explains how Spring Security’s Authentication interface represents an authentication request and identifies the methods needed to inspect it.
- Authentication request representation: Explain that Authentication represents an authentication request and holds details of the entity requesting access, called the principal. Describe how it extends Java Security’s Principal interface, aiding compatibility with other implementations.
Why it matters: It gives you the vocabulary for describing what an AuthenticationProvider receives and works with. - Authentication method meanings: Describe what isAuthenticated(), getCredentials(), and getAuthorities() return in this section’s account of the Authentication contract.
Why it matters: These are the contract methods the section identifies as necessary before implementing custom authentication logic.
Key terms: Authentication, principal, isAuthenticated(), getCredentials(), getAuthorities(), granted authorities
6.1.2 Implementing custom authentication logic
This section explains the AuthenticationProvider contract for custom authentication, including how a provider handles an Authentication request and how multiple providers can participate.
- Authentication provider responsibility: Explain that an AuthenticationProvider handles authentication logic, and that the default implementation uses UserDetailsService to find a user and PasswordEncoder to manage passwords during authentication.
Why it matters: It places custom authentication logic in the right Spring Security component. - Authentication method outcomes: Describe what authenticate() receives and what it should do on success, failure, or an unsupported request. Explain why a successful result is normally stripped of sensitive data such as the password.
Why it matters: These outcomes distinguish a successful login, a rejected login, and a request another provider may handle. - Provider support and delegation: Explain how supports() helps an authentication manager choose among providers, and distinguish recognition of an Authentication type from a provider's later decision to handle or reject a particular request.
Why it matters: Type support alone does not mean a particular request has been authenticated—or even handled by that provider.
Key terms: AuthenticationProvider, UserDetailsService, PasswordEncoder, authenticate(), Authentication, AuthenticationException, isAuthenticated(), supports(), AuthenticationManager
6.1.3 Applying custom authentication logic
This section shows how to implement and register a custom AuthenticationProvider, then explains why using Spring Security’s contracts is preferable to rebuilding its features.
- Supported authentication request type: Explain how a custom AuthenticationProvider declares which Authentication objects it supports, and why the example uses UsernamePasswordAuthenticationToken.
Why it matters: The provider needs to declare the kind of request its authentication logic is meant to handle. - Custom credential verification flow: Trace how the example authenticates a username-and-password request, including what happens when the user is missing, the password is wrong, or the password matches.
Why it matters: This is the decision the custom provider makes to accept or reject the request. - Custom provider registration: Describe how the example makes its custom AuthenticationProvider available to Spring and plugs it into the security configuration.
Why it matters: Writing a provider is not enough; the application must make it available and include it in its security configuration. - Framework contracts over reinvention: Justify why the section recommends using Spring Security’s intended contracts rather than rebuilding its security features as custom filter-chain code.
Why it matters: Using the framework’s extension points can avoid unnecessary custom security code that is hard to maintain.
Key terms: AuthenticationProvider, supports(), Authentication, UsernamePasswordAuthenticationToken, authenticate(), UserDetailsService, UserDetails, PasswordEncoder, matches(), AuthenticationException
6.2 Using the SecurityContext
Introduces the security context as the place Spring Security keeps a successful authentication and outlines how its storage changes across threads.
- Authenticated Details in Security Context: Explain that after successful authentication, the security context stores the Authentication object for the rest of the request, making details such as the current user's username and authorities available.
Why it matters: It explains where later security decisions can get information about the authenticated user. - Security Context Holding Strategies: Distinguish the three SecurityContextHolder strategies by whether the context belongs to each thread, is inherited by a new asynchronous thread, or is shared across all application threads.
Why it matters: The holding strategy determines which threads can see an authenticated user's details. - Contexts in Manually Created Threads: Explain why a thread created outside Spring does not automatically receive security-context details and what must be done if it needs them.
Why it matters: It prevents assuming that a manually created thread can automatically see the current authentication.
Key terms: SecurityContext, Authentication, SecurityContextHolder, MODE_THREADLOCAL, MODE_INHERITABLETHREADLOCAL, MODE_GLOBAL, @Async, security context, threads that are not known by Spring
6.2.1 Using a holding strategy for the security context
This subsection explains how the default security-context holding strategy isolates contexts by thread in servlet applications and how endpoint code can access the authenticated user.
- Thread-local security context isolation: Explain that Spring Security’s default MODE_THREADLOCAL strategy gives each request thread access to its own security context in a traditional servlet application. Describe why a newly created thread does not receive the original thread’s context details.
Why it matters: Thread isolation explains both why requests do not see one another’s security details and why a new thread cannot simply use the original thread’s details. - Accessing the authenticated entity: Describe how code can obtain the SecurityContext through SecurityContextHolder.getContext() after authentication and then obtain its Authentication object. Explain that Spring can instead inject Authentication directly into an endpoint method parameter.
Why it matters: These are the two access patterns the section gives for using authenticated-user details in application code.
Key terms: MODE_THREADLOCAL, ThreadLocal, security context, SecurityContextHolder, getContext(), Authentication, method parameters
6.2.2 Using a holding strategy for asynchronous calls
This section explains why an asynchronous method can lose access to the request’s security context and how an inheritable thread-local strategy addresses that case.
- Asynchronous security context gap: Explain why an @Async method may find Authentication null when the default security-context strategy is used.
Why it matters: It explains why authentication can be available during a request but missing inside its asynchronous method. - Inheritable context propagation limits: Describe how MODE_INHERITABLETHREADLOCAL addresses the asynchronous-thread problem, how the section says to select it, and when it does not suffice.
Why it matters: It identifies both the strategy that makes the example work and the boundary beyond which that strategy is not enough.
Key terms: MODE_THREADLOCAL, @Async, security context, Authentication, MODE_INHERITABLETHREADLOCAL, SecurityContextHolder.setStrategyName(), spring.security.strategy
6.2.3 Using a holding strategy for standalone applications
This section explains when to use a global security context, how to select it, and the concurrency risk it creates.
- Global context suitability: Explain that MODE_GLOBAL shares one security context across application threads and may suit a standalone application, but not a web server handling independent requests.
Why it matters: Choosing a holding strategy depends on whether threads should share an identity or requests should remain separate. - Global strategy selection: State the two ways the section gives for selecting MODE_GLOBAL.
Why it matters: These are the configuration options the section provides for choosing the global strategy. - Shared context concurrency risk: Explain why concurrent access needs attention when MODE_GLOBAL is used.
Why it matters: Sharing a context across threads introduces a concurrency concern that the strategy does not resolve for you.
Key terms: MODE_GLOBAL, security context, standalone application, SecurityContextHolder.setStrategyName(), spring.security.strategy, SecurityContext, thread safe, concurrent access
6.2.4 Forwarding the security context with DelegatingSecurityContextRunnable
This section explains why self-managed threads can lack the current security context and how task decorators propagate it.
- Security context in self-managed threads: Explain why a task run on a self-managed thread cannot assume it has the request thread’s security context, using the section’s Callable example.
Why it matters: It explains why code that reads authentication can fail when you move it to a thread you created. - Security context task decorators: Describe how the delegating task wrappers propagate the current security context, and distinguish which wrapper to use for a task with a return value.
Why it matters: The wrapper lets a separately executed task access the authentication that was missing in the undecorated example.
Key terms: security context, self-managed threads, authentication, DelegatingSecurityContextRunnable, DelegatingSecurityContextCallable<T>, Runnable, Callable<T>
6.2.5 Forwarding the security context with DelegatingSecurityContextExecutorService
This section explains how to propagate the security context to threads started by application code by decorating an ExecutorService rather than each task.
- ExecutorService security context propagation: Explain how DelegatingSecurityContextExecutorService propagates the security context when an application submits a task to an ExecutorService, and distinguish this from decorating each task.
Why it matters: It gives you a way to make security context details available in threads your code starts without decorating every task. - Alternative executor decorators: Distinguish the executor decorators named here by the contract each wraps and when the section suggests using it.
Why it matters: Choosing the decorator that matches your executor contract lets you propagate the context for scheduled work or retain flexibility in thread-pool implementation.
Key terms: DelegatingSecurityContextExecutorService, ExecutorService, Callable<T>, security context, DelegatingSecurityContextScheduledExecutorService, ScheduledExecutorService, DelegatingSecurityContextExecutor, Executor
6.3 Understanding HTTP Basic and form-based login authentications
This introduction explains why HTTP Basic has been useful for examples while cautioning that it may not suit every real-world application.
- HTTP Basic suitability: Explain why the book has used HTTP Basic for examples and why it may not fit every real-world scenario.
Why it matters: It helps you distinguish a convenient teaching example from a method you would choose for a particular application.
Key terms: HTTP Basic, proof of concept
6.3.1 Using and configuring HTTP Basic
This section shows how to configure HTTP Basic’s realm and customize failed-authentication responses.
- HTTP Basic realm configuration: Explain how an HTTP Basic realm name is configured and where it appears in the response.
Why it matters: A configured realm affects the challenge a client receives when authentication fails. - Custom failed-authentication response: Describe how to customize an HTTP Basic failure response with an AuthenticationEntryPoint and why its contents require care.
Why it matters: Clients may need a particular failure response, but that response must not disclose confidential information. - Exception-to-response bridge: Explain the stated role of ExceptionTranslationManager in authentication failures.
Why it matters: It connects an authentication exception to the HTTP failure response the client sees.
Key terms: HTTP Basic, Customizer, realmName(), WWW-Authenticate, AuthenticationEntryPoint, commence(), AuthenticationException, CustomEntryPoint, ExceptionTranslationManager, AccessDeniedException
6.3.2 Implementing authentication with form-based login
This section shows how to enable form-based login, serve a page after login, customize authentication outcomes, and optionally support HTTP Basic alongside the form.
- Form login configuration and defaults: Explain how to enable form-based login and what Spring Security provides with the minimal configuration.
Why it matters: A small configuration change gives a browser-based application a working login flow. - Homepage rendering after login: Describe why the example adds a homepage and how its controller renders HTML.
Why it matters: The login demonstration needs a browser-rendered destination to show where the user goes after authentication. - Successful login destinations: Explain the normal redirect after login and the two customization options introduced here.
Why it matters: It distinguishes the ordinary return-to-requested-page behavior from custom responses to a successful login. - Failed authentication handling: Explain when an AuthenticationFailureHandler is useful and how it is applied to form login.
Why it matters: Applications may need a failure response suited to their clients or operational needs. - Combined authentication methods: Distinguish the behavior of a form-login-only configuration from one that also enables HTTP Basic.
Why it matters: It explains why Basic credentials alone do not work after switching the example to form login.
Key terms: HttpSecurity, SecurityFilterChain, formLogin(), httpBasic(), home.html, /home, @Controller, @RestController, view, FormLoginConfigurer
6.4 Summary
Where this is used later
- Restricting access based on authorities and roles (chapter 7) · Authorization follows authentication and uses details about the requester.
- (chapter intro) (chapter 7) · Assumes the earlier discussion of authentication.
- Implementing multitenant systems (chapter 15) · The roles of authentication managers and providers in Spring Security authentication.
- User management in reactive apps (chapter 17) · The non-reactive authentication architecture used for comparison.
- Testing authentication (chapter 18) · the custom authentication logic being tested
- Restricting access for all endpoints based on user authorities (chapter 7) · Authority-based access rules depend on details of the authenticated user.
- Implementing permissions for methods (chapter 11) · The SecurityContext holds authentication information.
- Managing authorization for an OAuth 2 login (chapter 16) · The security context holds authentication details.
Concepts explained in this chapter
- AuthenticationProviderAuthenticationProvider is a Spring Security interface or component that encapsulates a specific authentication mechanism and returns an authentication result.
- custom authentication logicCustom authentication logic is application-defined processing that verifies a user's identity instead of relying entirely on a framework's default authentication behavior.
- form-based loginForm-based login is an authentication method in which a user submits credentials through an application-provided login form.
- supports()supports() is an AuthenticationProvider method that reports whether the provider can handle a specified Authentication type.
- mode_threadlocalMODE_THREADLOCAL is a SecurityContextHolder strategy mode that stores the security context in the current thread's local storage.
- security contextA security context is a Spring Security object that holds authentication information associated with the current execution or request.
- formLoginformLogin is a Spring Security configuration method that enables authentication through an HTML form-based login flow.
- SecurityContextHolderSecurityContextHolder is the Spring Security holder that associates a security context with the current execution thread or other configured scope.
- MODE_INHERITABLETHREADLOCALMODE_INHERITABLETHREADLOCAL is a Spring Security security-context strategy mode that makes a thread's context available to child threads through inheritable thread-local storage.
- CustomizerCustomizer is a Spring configuration functional interface whose callback applies customization to a framework configuration object.
- basic authenticationHTTP Basic authentication is an HTTP authentication scheme that transmits a username and password using an Authorization header value containing Base64-encoded credentials.
- httpBasichttpBasic is an HttpSecurity configuration method that enables HTTP Basic authentication.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
