Accessing User credentials in Spring 3 by using principal object.

The two most common ways to access the details for the logged in user in Spring 3 are:

  • Inside the JSP
  • Inside a java class (most likely to be used in the controller)

I personally much prefer to do this kind of things inside a java class. Nevertheless, here I will show both ways mentioned above.

  • Inside the JSP

Assuming now that we want to access the username of the logged in user, directly from the jsp. What we should do is, define the spring security taglib on the top of the jsp like this:
<%@ taglib prefix='security' uri='http://www.springframework.org/security/tags' %>

After we have define the above. Accessing username of logged in user is as simple as:
<security:authentication property="principal.username"/>

  • Inside a Java class

To access to user credentials here, we  will use the Principal object which is created for each logged in user. This is done like this:

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
UserDetails userDetails = null;
String username = null;
if (principal instanceof UserDetails) {
userDetails = (UserDetails) principal;
}
if (userDetails != null && userDetails.getUsername() != null) {
System.out.println("Username is: " + userDetails.getUsername());
}

I do mention both ways above, but it is always a good practise to keep logic outside from the jsp’s pages. So, I would strongly recommend to use the second way when you want access to UserDetails instances.

Futher Reading:

Interesting Video:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: