Category Archives: Security

Getting Logged On User in a Spring-Web Application

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

@Controllerpublic class PageController {
 
  @RequestMapping(method = RequestMethod.GET)
 
  public ModelAndView handleRequest() {
    User user = (User) SecurityContextHolder.getContext()
       .getAuthentication().getPrincipal();
    Map userModel = new HashMap();
    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}" />

Security for JSF Applications

I see a lot of posts around the internet by people asking what the standard mechanism for security is in JSF web applications.

From a security standpoint, JSF applications are no different from any other servlet based framework applications. If you’re deploying applications on J2EE / EE servers (e.g. GlassFish or JBoss) or even on Tomcat, then my first choice would be to use JAAS for security.

JAAS is straightforward to configure, is flexible and is a standard.

Next time you need to implement a security mechanism, I’d recommend you take a look at JAAS before embarking on writing custom security mechanisms. You never know – it may save you a lot of time.