I am using Spring MVC and Spring Security version 3.0.6.RELEASE. What is the easiest way to get the user name in my JSP? Or even just whether or not the user is logged in? I can think of a couple ways:
1. Using a scriptlet
Using a scriptlet like this to determine if the user is logged in:
<%=org.springframework.security.core.context.SecurityContextHolder.getContext()
.getAuthentication().getPrincipal().equals("anonymousUser")
? "false":"true"%>
I'm not a fan of using scriptlets, though, and I want to use this in some <c:if>
tags, which requires putting it back as a page attribute.
2. Using SecurityContextHolder
I could again use SecurityContextHolder from my @Controller
and put it on the model. I need this on every page, though, so I'd rather not have to add this logic in every one of my Controllers.
I suspect there's a cleaner way to do this...
I think
<sec:authentication property="principal.username" />
will not always work because type returned byAuthentication.getPrincipal()
is Object, ie: it could be a UserDetail (for which the above will work), a String or anything else.For purpose of displaying username in JSP page what I find more reliable is using
${pageContext.request.userPrincipal.name}
.This uses
java.security.Principal.getName()
which returns String.I know there are other answers in the thread, but none have answered how you can check if user is authenticated. So I'm sharing what my code look likes.
Include the tag lib in your project:
Then create a user object in current scope by adding:
Then you can easily show the username by adding. Remember the 'principal' object is generally of type string unless you have implemented the spring security in a way to change it to another Class in your project:
I hope this helps somebody looking to check user roles.
If you are using Maven, then add the dependency tag as mentioned by Christian Vielma in this thread.
Thanks!
As far as I know by default Spring Security 3.0.x installs a
SecurityContextHolderRquestAwareFilter
, so that you can get theAuthentication
object by callingHttpServletRequest.getUserPrincipal()
, and you can also query roles by callingHttpServletRequest.isUserInRole()
.You can use like this: Spring Security Tag Lib - 3.1.3.RELEASE
and Then:
Check Spring security tags :
<sec:authentication property="principal.username" />
http://static.springsource.org/spring-security/site/docs/3.0.x/reference/taglibs.html
And you can check if logged :
instead of c:if
This works whether user is logged in or not, and works when using Anonymous Authentication:
Later...