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

20 comments on “Get current logged in username in Spring Security

  1. 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

  2. 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

  3. 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

  4. 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.

  5. 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

  6. 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

  7. 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 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    	at java.lang.reflect.Method.invoke(Method.java:597)
    	at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:174)
    	at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:414)
    	at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:402)
    	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
    	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
    	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
    	at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:552)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:343)
    	at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
    	at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
    	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
    	at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
    	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
    	at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
    	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
    	at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
    	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
    	at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
    	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
    	at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
    	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
    	at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177)
    	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
    	at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
    	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
    	at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
    	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
    	at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
    	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
    	at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:149)
    	at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
    	at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    	at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
    	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
    	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
    	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
    	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
    	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
    	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
    	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
    	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    	at java.lang.Thread.run(Thread.java:619)
    
  8. 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

  9. 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;
    	}
    
    

Leave a Comment

Your email address will not be published. Required fields are marked *