Enterprise Java

What is SecurityContext and SecurityContextHolder in Spring Security?

The SecurityContext and SecurityContextHolder are two fundamental classes of Spring Security. The SecurityContext is used to store the details of the currently authenticated user, also known as a principle. So, if you have to get the username or any other user details, you need to get this SecurityContext first. The SecurityContextHolder is a helper class, which provide access to the security context. By default, it uses a ThreadLocal object to store security context, which means that the security context is always available to methods in the same thread of execution, even if you don’t pass the SecurityContext object around. Don’t worry about the ThreadLocal memory leak in web application though, Spring Security takes care of cleaning ThreadLocal.

Btw, that’s not the only way a SecurityContextHolder can store current SecurityContext, it can be configured with a strategy on startup to specify how you would the context to be stored. For example, you can use SecurityContextHolder.MODE_GLOBAL strategy for a standalone application.

The key thing to learn is that how do you get the SecurityContext from the SecurityContextHolder? and then retrieving current user details from that? For example, if you want to know the username of the current logged in user then how do you get that in Spring security?

In order to get the current username, you first need a SecurityContext, which is obtained from SecurityContextHolder. This SecurityContext keep the user details in an Authentication object, which can be obtained by calling getAuthentication() method.

Once you got the Authentication object, you can either cast into UserDetails or use it as it is. The UserDetails object is the one Spring Security uses to keep user-related information.

How to get the current logged-in Username in Spring Security

Here is the code to get the security context in Spring security and obtain the name of the currently logged in user:

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

if (principal instanceof UserDetails) {
  String username = ((UserDetails)principal).getUsername();
} else {
  String username = principal.toString();
}

The object returned by getContext() is an instance of the SecurityContext interface. This is the object that is stored in a thread-local storage.

The getPrincipal() method normally return UserDetails object in Spring Security, which contains all the details of currently logged in user.

Anyway, if you look closer, you will find that this is not really a nice code when we think about Spring and dependency injection. So if you ever need to know current logged-in user details e.g. in Spring MVC controller, I suggest you declare a dependency and let the Spring provide you the Principal object, rather you querying for them and create a tightly coupled system.

Here is an example of that

import java.security.Principal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MVCController {

  @RequestMapping(value = "/username", method = RequestMethod.GET)
  @ResponseBody
  public String currentUserName(Principal principal) {
     return principal.getName();
  }

}

Alternatively, you can also ask for Authentication object instead of a Principal object as shown below:

import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class SpringMVCController {

  @RequestMapping(value = "/username", method = RequestMethod.GET)
  @ResponseBody
  public String currentUserName(Authentication authentication) {
     return authentication.getName();
  }
}

If you want to know more ways, you can also see my post about 3 ways to get the current username in Spring Security, where I have discussed a couple of more ways to retrieve the current username in Spring MVC controller.

That’s all about what is security context in Spring security and how you can obtain a SecurityContext from SecurityContextHolder class. These are some of the fundamental classes, hence you must be familiar with them.

The storage part i.e. SecurityContext is stored in ThreadLocal is optional, but it’s also good to know the detail. Just remember, if you ever need user details e.g. username etc, you better ask for Principal or Authentication object in Spring MVC controller, rather than using SecurityContextHolder to obtain them.

Thanks for reading this article so far. If you like this Spring Security tutorial then please share with your friends and colleagues. If you have any questions or feedback then please drop a note.

Published on Java Code Geeks with permission by Javin Paul, partner at our JCG program. See the original article here: What is SecurityContext and SecurityContextHolder in Spring Security?

Opinions expressed by Java Code Geeks contributors are their own.

Javin Paul

I have been working in Java, FIX Tutorial and Tibco RV messaging technology from past 7 years. I am interested in writing and meeting people, reading and learning about new subjects.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button