Get current logged in username in Spring Security
In this article, we will show you three ways to get the current logged in username in Spring Security.
1. SecurityContextHolder + Authentication.getName()
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class LoginController {
@RequestMapping(value="/login", method = RequestMethod.GET)
public String printUser(ModelMap model) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName(); //get logged in username
model.addAttribute("username", name);
return "hello";
}
//...
2. SecurityContextHolder + User.getUsername()
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class LoginController {
@RequestMapping(value="/login", method = RequestMethod.GET)
public String printUser(ModelMap model) {
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String name = user.getUsername(); //get logged in username
model.addAttribute("username", name);
return "hello";
}
//...
3. UsernamePasswordAuthenticationToken
This is more elegant solution, in runtime, Spring will injects UsernamePasswordAuthenticationToken
into the Principal
interface.
import java.security.Principal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class LoginController {
@RequestMapping(value="/login", method = RequestMethod.GET)
public String printWelcome(ModelMap model, Principal principal ) {
String name = principal.getName(); //get logged in username
model.addAttribute("username", name);
return "hello";
}
//...
Download Source Code
Download it – Spring-Security-Get-Logged-In-Username.zip (9 KB)
how can retrieve userid using spring security?
We used this way of getting logged in UserDetails from SecurityContextHolder.getContext().getAuthentication().getPrinicipal().getUsername(). But it seems, it is not behaving thread safe.
Suppose multiple active session exists for a web applcation, I can see different threads created by different sessions for any request but the user id returned by SecurityContext sometimes is not correct. It returns UserId of userA for any operation done by UserB.
My Code:
public static String getId() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
Object principal = auth.getPrincipal();
if (principal instanceof UserWithId) {
return ((UserWithId) principal).getUserid();
}
}
return null;
}
Does it requires any configuration which I missed. Please help
I’m facing similar issue. Did you find a solution for this?
Hi, this is very helpful example. I have one question if I want to get all details of logged in user (i.e his/her user_id,name,email,dob etc.) then how can I get those details using org.springframework.security.core.Authentication or thie any other way to get these all deatils.
Thank you.
Thanks a lot mkyong, really save my time
i have 200 to 300 request mapping i am not interested to repeat same line of code, How to overcome
TIA
i achieved this by placed
code in head jsp and included all files
hi MKyong,
your tutorial helped me a lot…I have a question related to login page …actually i have login table in my database from where i have to check the entered username and password …and i have different roles as admin and user
If you need this to work in an aspect, you need to add the following bean to your application (root) context:
org.springframework.security.core.context.SecurityContextHolder
setStrategyName
MODE_INHERITABLETHREADLOCAL
Can give an example where in the XML you need put this…can’t find any working example
Thanks dude, love your posts
Very helpful post! Thank you!
hi mkyong,
can we get password using Principal as we get username
best regards,
rajesh
Hi Mkyong,
I have to say thank you. Your tutorials had helped me a lot. I have a question related to how to get the current username. I have a table in MySQL with some fields (username, password, enabled, name) my question is: Is there anyway to return the value of the “name” field in that table? and how can i do that?
Thanks in advance.
Greetings
Hi mkyong, i’m trying to get the userPrincipal from any bean in my JSF application, but i’m getting a null pointer. I think that is because the spring getContext uses a ThreadLocal.
Do you have any idea ?
See this post:
http://www.lejava.com.br/java/jsf/jsf-2-spring-spring-security-3-and-database
Do you know if i use @ManagedProperty in any Bean, i will get the userPrincipal correctly ?
Thanks in advance
i am spring security in my current project..i have following code in springsecurity.taglib.xml
http://www.springframework.org/security/tags
authorize
org.springframework.faces.security.FaceletsAuthorizeTagHandler
areAllGranted
org.springframework.faces.security.FaceletsAuthorizeTagUtils
boolean areAllGranted(java.lang.String)
areAnyGranted
org.springframework.faces.security.FaceletsAuthorizeTagUtils
boolean areAnyGranted(java.lang.String)
areNotGranted
org.springframework.faces.security.FaceletsAuthorizeTagUtils
boolean areNotGranted(java.lang.String)
isAllowed
org.springframework.faces.security.FaceletsAuthorizeTagUtils
boolean isAllowed(java.lang.String, java.lang.String)
i want add new tag authentication…how can i add that
pls help me
first of all, your site is very helpful . It makes things a whole lot easier for me.
I m trying your first example , i am unable to get the authentication object .
“Authentication auth = SecurityContextHolder.getContext().getAuthentication();”
i am getting null value. I m following your code , but i m not able to figure out how to resolve this. Following is the error message generated for me.
I think you mean RequestMapping as “/welcome” instead of “/login” that you have put. You will get hold of principal (USer) only after successful authentication.
– K. Arun
Come ti permetti ? 😉 mkyoung sa il fatto suo 😉
This is my login function