1. Introduction

Welcome to Spring Security’s hands-on dry goods series. In the previous two articles we covered configuring access control based on configuration and annotating. Today we will look at how to retrieve current authenticated user information in interface access. Let’s start with a concrete scenario. Generally, information about the current authenticated user is required to access the resources to be authenticated after authentication. For example, “Check my personal information.” It is definitely not appropriate to pass in your UserID explicitly on interface access. The system knows who you are because you are authenticated and access resources. It is also unsafe to explicitly expose the user’s retrieval interface. So we need a tool in the business that can retrieve the current authenticated user. Let’s look at how Spring Security addresses this pain point.

2. SecurityContext SecurityContext

The JwtAuthenticationFilter is used to implement the JWT authentication interceptor. When the service side of JWT Token authentication through after, will authenticate the user information encapsulation to UsernamePasswordAuthenticationToken And use the tools in the security context SecurityContext, When the server responds to user and then use the same tools will UsernamePasswordAuthenticationToken clear away from SecurityContext. Let’s take a quick look at what a SecurityContext is.

 package org.springframework.security.core.context;
 
 import java.io.Serializable;
 import org.springframework.security.core.Authentication;
 
 public interface SecurityContext extends Serializable {
     Authentication getAuthentication(a);
 
     void setAuthentication(Authentication var1);
 }
Copy the code

From the source is very simple is a storage Authentication container. Whereas Authentication is a user credential interface used as a credential for user Authentication, Usually there are authenticated user to implement the common UsernamePasswordAuthenticationToken AnonymousAuthenticationToken and anonymous users. UsernamePasswordAuthenticationToken include the populated UserDetails, AnonymousAuthenticationToken contains only one string anonymousUser as anonymous user’s identity. We need to make type judgments when we get the context through the SecurityContext. Let’s talk about the utility class that operates on SecurityContext.

3. SecurityContextHolder

This tool class is SecurityContextHolder. It provides two useful methods:

  • clearContextClear currentSecurityContext
  • getContextGet the currentSecurityContext
  • setContextSet the currentSecurityContext

Normally, we operate the SecurityContext SecurityContext in these three ways. You can retrieve user information directly in your code using the utility class SecurityContextHolder, as follows:

 public String getCurrentUser(a) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
          
     if (authentication instanceof AnonymousAuthenticationToken){
         return "anonymousUser";
     }
    UserDetails principal = (UserDetails) authentication.getPrincipal();
    return principal.getUsername();
 }     
Copy the code

3.1 Extended Knowledge: Storage policy for SecurityContextHolder

Here, as an extension, we’ll briefly talk about how the SecurityContextHolder stores the SecurityContext. By default, SecurityContextHolder has three policies for storing SecurityContext:

  • MODE_THREADLOCALusingThreadLocalMechanism to save each user’sSecurityContext.The default policyWe usually use this one.
  • MODE_INHERITABLETHREADLOCALusingInheritableThreadLocalMechanism to save each user’sSecurityContext, mainly used in multi-threaded environment.
  • MODE_GLOBAL Static mechanism that applies globally. Not very often.

4. To summarize

SecurityContext is one of the most important classes in Spring Security. Today we will review what SecurityContext is and what it does. We also explained how to use the SecurityContextHolder to manipulate the SecurityContext. Finally, three strategies for storing SecurityContextHolder and their usage scenarios are briefly described. I hope it will be helpful for you to learn Spring Security. Please pay attention.

Follow our public id: Felordcn for more information

Personal blog: https://felord.cn