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

Getting Logged On User in a Spring-Web Application

DZone's Guide to

Getting Logged On User in a Spring-Web Application

· Java Zone
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

In a web application, it can be useful to get the logged on user's name and display it within a web page, for example as a link to allow the user to edit their profile.  In a Spring Web application the username can easily be obtained in a controller and passed via a map to the user interface.

To get the username in a controller class, we would use the SecurityContextHolder.getContext().getAuthentication().getPrincipal() method to get hold of the principal. We can then call the .getUsername() method to get the username of the currently logged on user.

@Controller
public class PageController {
 
  @RequestMapping(method = RequestMethod.GET)
 
  public ModelAndView handleRequest() {
    User user = (User) SecurityContextHolder.getContext()
        .getAuthentication().getPrincipal();
    Map<String, Object> userModel = new HashMap<String, Object>();
    userModel.put("username", user.getUsername());
    return new ModelAndView("page", "model", userModel);
  }
}

The username can then be displayed in an HTML page as:
<c:out value="${model.username}" />

From http://www.davidsalter.com/2012/01/getting-logged-on-user-in-spring-web.html

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}