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
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.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

  • Pingback: ionizer payment plan()

  • Pingback: house blue()

  • Pingback: zak?ad szklarski piotrk√≥w trybunalski()

  • Pingback: get more information()

  • Pingback: plumbing fixtures kohler()

  • Pingback: locksmiths seattle()

  • Pingback: site here()

  • Pingback: auto electrician jobs africa()

  • Pingback: at&t electrician salary()

  • Pingback: water ionizer pay plan loans()

  • Pingback: paypal loans()

  • Pingback: alkaline water brands()

  • Pingback: laan penge()

  • Pingback: water ionizer()

  • Pingback: stop parking()

  • Pingback: mobile porn movies()

  • Pingback: car parking()

  • Pingback: tv packages()

  • Pingback: Blue Coaster33()

  • 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

  • Silvio

    Thanks dude, love your posts

  • 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

    Very helpful post! Thank you!

  • rajesh

    hi mkyong,

    can we get password using Principal as we get username

    best regards,
    rajesh

  • 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

    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

  • Pingback: GAE?SpringMVC???????4(? Spring Security ??????) | Walk on apps.()

  • Pingback: GAE?SpringMVC???????4(? Spring Security ??????) | Walk on apps.()

  • Pingback: GAE?SpringMVC???????4(? Spring Security ??????) | Walk on apps.()

  • jatin

    how can retrieve userid using spring security?

  • http://as 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

    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)
  • http://ramlabs.wordpress.com 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

    • http://www.antonioacciardo.it antonioa89

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

  • http://www.j2eevideotutorial.com/search/label/Spring%20Security?&max-results=21 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;
    	}
  • Pingback: Spring Security form login example (authentication)()