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

References

  1. SecurityContextHolder JavaDoc
  2. User JavaDoc
  3. UsernamePasswordAuthenticationToken JavaDoc

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Mona
Guest
Mona

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

Abhimanyu Seth
Guest
Abhimanyu Seth

I’m facing similar issue. Did you find a solution for this?

klepontech.id
Guest
klepontech.id

Thanks a lot mkyong, really save my time

Salman
Guest
Salman

i have 200 to 300 request mapping i am not interested to repeat same line of code, How to overcome
TIA

Salman
Guest
Salman

i achieved this by placed

code in head jsp and included all files

priya
Guest
priya

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

skin27
Guest
skin27

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

Jeff
Guest
Jeff

Can give an example where in the XML you need put this…can’t find any working example

Silvio
Guest
Silvio

Thanks dude, love your posts

pravin
Guest
pravin

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.

sourcerix
Guest
sourcerix

Very helpful post! Thank you!

rajesh
Guest
rajesh

hi mkyong,

can we get password using Principal as we get username

best regards,
rajesh

Cesar123
Guest
Cesar123

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

Sandro Simas
Guest
Sandro Simas

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

trackback
GAE?SpringMVC???????4(? Spring Security ??????) | Walk on apps.

[…] ???????????? ???????????????????????????????????????? Controller??????????????????????????? Get current logged in username in Spring Security […]

trackback
GAE?SpringMVC???????4(? Spring Security ??????) | Walk on apps.

[…] ???????????? ???????????????????????????????????????? Controller??????????????????????????? Get current logged in username in Spring Security […]

trackback
GAE?SpringMVC???????4(? Spring Security ??????) | Walk on apps.

[…] ???????????? ???????????????????????????????????????? Controller??????????????????????????? Get current logged in username in Spring Security […]

jatin
Guest
jatin

how can retrieve userid using spring security?

bala
Guest
bala

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

atri
Guest
atri
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. SEVERE: Servlet.service() for servlet [dispatcher] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause java.lang.NullPointerException at com.mkyong.common.controller.LoginController.printWelcome(LoginController.java:19) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at… Read more »
Arun
Guest
Arun

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

antonioa89
Guest
antonioa89

Come ti permetti ? ;) mkyoung sa il fatto suo ;)

Spring Security Framework Video Tutorial
Guest
Spring Security Framework Video Tutorial

This is my login function

public String logar() {
		try {
		    RequestDispatcher dispatcher = FacesUtil.getServletRequest().getRequestDispatcher("/j_spring_security_check");
		    dispatcher.forward(FacesUtil.getServletRequest(), FacesUtil.getServletResponse());
		    FacesContext.getCurrentInstance().responseComplete();
		    HttpSession session = FacesUtil.getServletRequest().getSession();
			current = FacesUtil.getPrincipal(session);
			if(current!=null)
				{System.out.println("Username="+current.getUsername());
			     role = current.getAuthority();
				}
			else
				System.out.println("Null User");
		} catch (Exception ex) {
			FacesUtil.exibirMensagemErro(ex.getMessage());
			return null;
		}
	    return null;
	}

trackback
Spring Security form login example (authentication)

[…] MVC ControllerSpring controller to handle what URL should go where. Note You may interest at this how to get the current logged user detail.File : LoginController.javapackage com.mkyong.common.controller;   import […]