Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Access the Current Logged-In Username in Spring Security

DZone 's Guide to

How to Access the Current Logged-In Username in Spring Security

Need help finding the current logged-in username in Spring Security? Check out this post to learn how using the SecurityContext and SecurityContextHolder classes.

· Security Zone ·
Free Resource

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 the SecurityContext first.

The SecurityContextHolder is a helper class that provides 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 your web application though, Spring Security takes care of cleaning the ThreadLocal.

By the way, 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: 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 the SecurityContextHolder. This  SecurityContext  kepy the user details in an Authentication object, which can be obtained by calling the getAuthentication()  method.

Once you got the Authentication object, you can either cast it into UserDetails or use it as it is. The  UserDetails  object is the one that 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 SecurityContext 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 returns UserDetails object in Spring Security, which contains all the details of currently logged in user. If you are just starting with Spring Security and not familiar with these concepts, then you should first go through Spring Security Fundamentals, which explains most of the Spring Security fundamentals in simple language. 

What is SecurityContext and SecurityContextHolder in Spring Security?

Alternatively, you can also join Learn Spring Security Masterclass by Eugen Paraschiv, which is slightly expensive but full of real-world examples and lots of hands-on coding, so you can apply the knowledge you learned.

Anyway, if you look closer, you will find that this is not really a nice code when we think about Spring and the dependency injection.

So, if you ever need to know the current logged-in user details, e.g. in Spring MVC controller, I suggest you declare a dependency and let Spring provide you the Principal object, rather you querying for them and creating 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 the 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 learn more ways, you can also see my post about three 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 security context in Spring Security and how you can obtain a SecurityContext from the SecurityContextHolder class. These are some of the fundamental classes, hence you must be familiar with them.

The storage part, i.e. SecurityContext, that 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 the Principal or Authentication object in Spring MVC controller, rather than using the SecurityContextHolder to obtain them.

Other Spring Security articles and resources you may like to explore:
Spring Framework 5: Beginner to Guru
5 Courses to Learn Spring Security Online
How to enable Spring Security in Java Web Application?
How to enable HTTP Basic Authentication using Spring Security?
How HttpBasicAutentication works in Spring Security?
Learn Spring Security: The Certification Class

Thanks for reading this tutorial. If you like this tutorial, then please share with your friends and colleagues. If you have any questions or feedback, then please drop a note below! 

Topics:
spring ,spring mvc ,spring security ,java ,web developement ,security

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}