-
Notifications
You must be signed in to change notification settings - Fork 191
How to Get Current Logged In Username in JSP using Spring Security
Spring Security has its own spring-security-taglibs library, which provides basic support for accessing security information and applying security constraints in JSPs.
First of all, let’s add the spring-security-taglibs dependency to our pom.xml:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>Now, before we can use the tags, we need to import the taglib at the top of our JSP file:
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>After adding this, we’ll be able to specify Spring Security’s tags with the sec prefix.
The currently authenticated principal or user can access in JSP pages, by leveraging the spring security taglib support. First, we need to define the tag in the page:
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>Next, we can refer to the principal:
<security:authorize access="isAuthenticated()">
authenticated as <security:authentication property="principal.username" />
</security:authorize>Let's understand the above spring security tags in briefly.
Spring provides basically 3 tags for securing view layer information i.e.
- authorize tag
- authenticate tag
- accesscontrollist tag
This tag is used to determine whether its contents should be evaluated or not. This tag has two flavors i.e. securing information based on user’s role or securing information based on user’s permission to access a particular URL.
<security:authorize access="isAuthenticated()">This tag allows access to the current Authentication object stored in the security context. It renders a property of the object directly in the JSP. So, for example, if the principal property of the Authentication is an instance of Spring Security’s UserDetails object, then using <sec:authentication property=”principal.username”></sec:authentication> will render the name of the current user.
This tag is not for security purpose directly, but it can be used for accessing information which can be used for view layer security.
<security:authentication property="principal.username" />This tag is only valid when used with Spring Security’s ACL module. It checks a comma-separated list of required permissions for a specified domain object. If the current user has any of those permissions, then the tag body will be evaluated. If they don’t, it will be skipped.
<sec:accesscontrollist hasPermission="1,2" domainObject="someObject">
This will be shown if the user has either of the permissions
represented by the values "1" or "2" on the given object.
</sec:accesscontrollist>