Get Spring Security Principal in JSP EL expression
I was using Maven so I had to add the taglibs library adding this to the pom.xml
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>3.1.3.RELEASE</version>
</dependency>
Then in my jsp added:
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
And:
<sec:authentication property="principal" />
principal.username
kept giving me errors (maybe is the way I created the UsernamePasswordAuthenticationToken
object, not sure).
You can use like this: Spring Security Tag Lib - 3.1.3.RELEASE
<sec:authentication var="principal" property="principal" />
and Then:
${principal.username}
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 :
<sec:authorize access="isAuthenticated()">
instead of c:if
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:
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
Then create a user object in current scope by adding:
<sec:authentication var="user" property="principal" />
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:
<sec:authorize access="hasRole('ROLE_USER') and isAuthenticated()">
${user}
</sec:authorize>
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!