Spring Security part V : Security tags

Today we discuss about the security tags provided with Spring Security package. These tags allow you to customize your web pages to include/exclude elements based on user roles and credentials

The below description of Spring Security Tag is based on official Spring Security 3.1.0 RELEASE. It may not apply to older versions

I Configuration

To enable JSP page-level security, we need to import the Spring Security tag library as follow:

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

We also need to add the spring security taglib Maven dependency into our project pom.xml

  	<dependency>
  		<groupId>org.springframework.security</groupId>
  		<artifactId>spring-security-taglibs</artifactId>
  		<version>3.1.0.RELEASE</version>
  		<type>jar</type>
  		<scope>compile</scope>
  	</dependency>

II Security tags

 

A The Authorization tag

To enable the rendering of some portion based on user credentials, we can rely on the <sec:authorize> tag:

&lt;sec:authorize access=&quot;hasRole('admin')&quot;&gt;
	&lt;table&gt;
  		&lt;tr&gt;
  	  	  	&lt;td&gt;xxx&lt;/td&gt;
  	  	  	&lt;!-- Some administrator data here --&gt;
  	  	&lt;/tr&gt;
  	&lt;/table&gt;
&lt;/sec:authorize&gt;

&lt;sec:authorize access=&quot;hasRole('guest')&quot;&gt;
	Restricted data, you are not allowed to access this resource  	
&lt;/sec:authorize&gt;

The “access” attribute allows us to define the access rules. In the above example we simply check for user role (admin or guest). The hasRole is a SpEL (Spring Expression Language) syntax. Complete list of spEL expressions for security is given below:

  • hasRole([role]): Returns true if the current principal has the specified role.
  • hasAnyRole([role1,role2]): Returns true if the current principal has any of the supplied roles (given as a comma-separated list of strings)
  • principal: Allows direct access to the principal object representing the current user
  • authentication: Allows direct access to the current Authentication object obtained from the SecurityContext
  • permitAll: Always evaluates to true
  • denyAll: Always evaluates to false
  • isAnonymous(): Returns true if the current principal is an anonymous user
  • isRememberMe(): Returns true if the current principal is a remember-me user
  • isAuthenticated(): Returns true if the user is not anonymous
  • isFullyAuthenticated(): Returns true if the user is not an anonymous or a remember-me user

Among this list, only some expressions are usefull for the access attribute, mainly hasRole([role]), hasAnyRole([role1,role2]), isAnonymous(), isRememberMe(), isAuthenticated() and isFullyAuthenticated(). The other expressions are more informative and serve in different contexts (we’ll see them soon)

Apart from the “access” attribute, the <sec:authorize> tag offers other interesting attributes:

  • url: an URL within the application. The tag <sec:authorize> is renderd if the user is grated access to this URL (based on rules defined by the FilterSecurityInterceptor)
  • method: GET or POST. Specify the HTTP method user to access the url. This attribute can only be used along with the previous url attribute.
  • var: a page scope variable to store the evaluation of this tag (true or false) so it can be re-used later in the page for different purpose.

Please note that for the “url” attribute to work, you need to declare an additional DefaultWebInvocationPrivilegeEvaluator bean in the Spring context with the filterSecurityInterceptor injected as constructor argument:

&lt;!-- Filter for role checking --&gt;
&lt;bean id=&quot;filterSecurityInterceptor&quot; class=&quot;org.springframework.security.web.access.intercept.FilterSecurityInterceptor&quot;&gt;
	&lt;property name=&quot;authenticationManager&quot; ref=&quot;authenticationManager&quot;/&gt;
	&lt;property name=&quot;accessDecisionManager&quot; ref=&quot;httpRequestAccessDecisionManager&quot;/&gt;
	&lt;property name=&quot;securityMetadataSource&quot;&gt;
		&lt;sec:filter-security-metadata-source lowercase-comparisons=&quot;true&quot; request-matcher=&quot;ant&quot; use-expressions=&quot;true&quot;&gt;
			&lt;sec:intercept-url pattern=&quot;/pages/Security/**&quot; access=&quot;permitAll&quot;/&gt;
			&lt;sec:intercept-url pattern=&quot;/resources/**&quot; access=&quot;permitAll&quot;/&gt;
			&lt;sec:intercept-url pattern=&quot;/pages/Settings/**&quot; access=&quot;hasRole('SETTINGS')&quot;/&gt;
			&lt;sec:intercept-url pattern=&quot;/pages/Home/*&quot; access=&quot;hasRole('HOME')&quot;/&gt;              
			&lt;sec:intercept-url pattern=&quot;/pages/Admin/**&quot; access=&quot;hasRole('ADMINISTRATOR')&quot;/&gt;
			&lt;sec:intercept-url pattern=&quot;/servlet/Download&quot; access=&quot;hasAnyRole('DOWNLOAD','PREMIUM_ACCOUNT')&quot;/&gt;
                
			&lt;sec:intercept-url pattern=&quot;/**&quot; access=&quot;isAuthenticated()&quot;/&gt;
		&lt;/sec:filter-security-metadata-source&gt;
	&lt;/property&gt;
&lt;/bean&gt;

&lt;!-- webInvocationPrivilegeEvaluator necessary to use &lt;sec:authorized url=&quot;xx&quot;&gt; --&gt;
&lt;bean id=&quot;webInvocationPrivilegeEvaluator&quot; class=&quot;org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator&quot;&gt;
	&lt;constructor-arg ref=&quot;filterSecurityInterceptor&quot;&gt;
&lt;/bean&gt;

Below is an example of the var attribute usage:

&lt;sec:authorize access=&quot;hasRole('admin')&quot; var=&quot;isAdmin&quot;&gt;
	&lt;table&gt;
  		&lt;tr&gt;
  	  	  	&lt;td&gt;xxx&lt;/td&gt;
  	  	  	&lt;!-- Some administrator data here --&gt;
  	  	&lt;/tr&gt;
  	&lt;/table&gt;
&lt;/sec:authorize&gt;
...
&lt;c:if test=&quot;${isAdmin}&quot;&gt;
  // Some block here if the user is Admin
&lt;/c:if&gt;

 

B The Authentication tag

The &ltsec:authentication> tag gives access to the Authentication object of the security context. The attribute “property” allows us to access some property of the Authentication object itself and display it directly to the page.

The Authentication interface exposes the following methods:

  • authorities: collection of GrantedAuthority instances. Corresponds in most case to user roles
  • credentials: user’ credentials (usually password)
  • details: object containing the details of the authentication process itself. The content of this object depends on the implementation of the Authentication interface. The default implementation returns null
  • principal: the principal object, which is most of the time an instance of the UserDetails interface
  • isAuthenticated: return true or false whether the use is authenticated or not

As with the previous tag, the &ltsec:authentication> tag offers some interesting other attributes:

  • var: a page variable to store the result of the property attribute so it can be re-used later in the page for different purposes
  • scope: scope of the above “var” attribute. Can be “page“, “request“,”session” or “application
  • htmlEscape: if true, enable HTML escape for the “property” attribute display

Usage examples:

&lt;!-- Credentials display --&gt;
Your password is &lt;sec:authentication property=&quot;credentials&quot;/&gt;
...

&lt;!-- Roles display --&gt;
&lt;sec:authentication property=&quot;authorities&quot; var=&quot;roles&quot; scope=&quot;page&quot; /&gt;
Your roles are:
&lt;ul&gt;
	&lt;c:forEach var=&quot;role&quot; items=&quot;${roles}&quot;&gt;
 	&lt;li&gt;${role}&lt;/li&gt;
	&lt;/c:forEach&gt;
&lt;/ul&gt;

&lt;!-- Username display --&gt;
Your username is &lt;sec:authentication property=&quot;principal.username&quot;/&gt;

 

C The Accesscontrollist tag

This <sec:accesscontrollist> tag is rarely used and can only be evaluated if Spring Security’s ACL module is activated.

The available attributes are:

  • hasPermission: a list of permission (coma as separator) to be checked against domain object. The permission strings will be converted first into Permission instance by the PermissionFactory before performing evaluation. The evaluation is true if at least one of the listed permission is found in the domain object
  • domainObject: domain object for which the above permissions are evaluated
  • var: a page scope variable to store the evaluation of this tag (true or false) so it can be re-used later in the page for different purpose

Usage example:


&lt;sec:accesscontrollist hasPermission=&quot;admin,designer&quot; domainObject=&quot;${someObject}&quot;&gt;
	//Displayed only if the domainObject has &quot;admin&quot; OR &quot;designer&quot; permission  
&lt;/sec:accesscontrollist&gt; 

III Security tags for Facelet

The above security tags are only available for JSP pages. If you are a JSF-user with Facelet as templating solution, no chance.

Luckily, some brillant people had a good idea to adapt these tags for Facelet. You can download the binaries here http://www.dominikdorn.com/facelets/

By looking around, I found out that there is a tag library out there for JSF shipped with Spring Web Flow: http://static.springsource.org/spring-webflow/docs/2.2.x/reference/html/ch13s09.html

You need to add the following dependency to your pom.xml

&lt;dependency&gt;
	&lt;groupId&gt;org.springframework.webflow&lt;/groupId&gt;
	&lt;artifactId&gt;spring-faces&lt;/artifactId&gt;
	&lt;version&gt;2.2.0.RELEASE&lt;/version&gt;
&lt;/dependency&gt;

This jar contains many packages, among others the org.springframework.faces.security which is of interest. Alternatively if you do not want to get all the packages not related to security you can just copy the org.springframework.faces.security package into your source code.

Adding the above dependency is not enough. You need also to declare this new taglib in a springsecurity.taglib.xml file for example:

&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;!DOCTYPE facelet-taglib PUBLIC
  &quot;-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN&quot;
  &quot;http://java.sun.com/dtd/facelet-taglib_1_0.dtd&quot;&gt;
&lt;facelet-taglib&gt;
	&lt;namespace&gt;http://www.springframework.org/security/tags&lt;/namespace&gt;
	&lt;tag&gt;
		&lt;tag-name&gt;authorize&lt;/tag-name&gt;
		&lt;handler-class&gt;org.springframework.faces.security.FaceletsAuthorizeTagHandler&lt;/handler-class&gt;
	&lt;/tag&gt;
	&lt;function&gt;
		&lt;function-name&gt;areAllGranted&lt;/function-name&gt;
		&lt;function-class&gt;org.springframework.faces.security.FaceletsAuthorizeTagUtils&lt;/function-class&gt;
		&lt;function-signature&gt;boolean areAllGranted(java.lang.String)&lt;/function-signature&gt;
	&lt;/function&gt;
	&lt;function&gt;
		&lt;function-name&gt;areAnyGranted&lt;/function-name&gt;
		&lt;function-class&gt;org.springframework.faces.security.FaceletsAuthorizeTagUtils&lt;/function-class&gt;
		&lt;function-signature&gt;boolean areAnyGranted(java.lang.String)&lt;/function-signature&gt;
	&lt;/function&gt;
	&lt;function&gt;
		&lt;function-name&gt;areNotGranted&lt;/function-name&gt;
		&lt;function-class&gt;org.springframework.faces.security.FaceletsAuthorizeTagUtils&lt;/function-class&gt;
		&lt;function-signature&gt;boolean areNotGranted(java.lang.String)&lt;/function-signature&gt;
	&lt;/function&gt;
	&lt;function&gt;
		&lt;function-name&gt;isAllowed&lt;/function-name&gt;
		&lt;function-class&gt;org.springframework.faces.security.FaceletsAuthorizeTagUtils&lt;/function-class&gt;
		&lt;function-signature&gt;boolean isAllowed(java.lang.String, java.lang.String)&lt;/function-signature&gt;
	&lt;/function&gt;
	&lt;function&gt;
		&lt;function-name&gt;access&lt;/function-name&gt;
		&lt;function-class&gt;org.springframework.faces.security.FaceletsAuthorizeTagUtils&lt;/function-class&gt;
		&lt;function-signature&gt;boolean access(java.lang.String)&lt;/function-signature&gt;
	&lt;/function&gt;	
&lt;/facelet-taglib&gt;

The above declaration sheds some light on the available infrastructure:

  • authorize: new tag
  • areAllGranted(roles): new EL function. Returns true if all listed roles are granted to the current user
  • areAnyGranted(roles): new EL function. Returns true if at least one listed role is granted to the current user
  • areNotGranted(roles): new EL function. Returns true if all listed roles are not granted to the current user
  • isAllowed(url,method): new EL function. Returns true if the given url with corresponding HTTP method can be accessed by the current user
  • access(webExpression): new EL function. Returns true if the given web expression holds for the current user

The tag exposes the following attributes:

  • access: see above
  • url: see above
  • method: see above
  • areAllGranted: see above
  • areAnyGranted: see above
  • areNotGranted: see above
  • var: set the result of the access evaluation (true or false) into the Faces context

We need to declare this taglib in the web.xml file:

&lt;context-param&gt;
	&lt;param-name&gt;javax.faces.FACELETS_LIBRARIES&lt;/param-name&gt;
	&lt;param-value&gt;/WEB-INF/springsecurity.taglib.xml&lt;/param-value&gt;
&lt;/context-param&gt;

Usage example:

&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;
      xmlns:ui=&quot;http://java.sun.com/jsf/facelets&quot; 
      xmlns:h=&quot;http://java.sun.com/jsf/html&quot;
      xmlns:f=&quot;http://java.sun.com/jsf/core&quot;
      xmlns:sec=&quot;http://www.springframework.org/security/tags&quot;&gt;
&lt;ui:composition template=&quot;/pages/Templates/techWebTemplate.xhtml&quot;&gt;
	...
	...
	&lt;h:panelGroup  id=&quot;secureBlock&quot; layout=&quot;block&quot;
		rendered=&quot;#{sec:areAnyGranted('DESIGNER, ADMINISTRATOR')}&quot;&gt;
		// Section rendered only for DESIGNER or ADMINISTRATOR roles
	&lt;/h:panelGroup&gt;						
	...
	...
	&lt;sec:authorize access=&quot;hasAnyRole('ADMINISTRATOR',&quot;DESIGNER')&quot;&gt;
		&lt;h:panelGroup id=&quot;administrationBlock&quot; layout=&quot;block&quot;&gt;
		...
		&lt;/h:panelGroup&gt;
	&lt;/sec:authorize&gt;    
&lt;/ui:composition&gt;
&lt;/html&gt;

Please pay attention to the special typo for the tag version and the EL function version.

<sec:areAnyGranted(‘DESIGNER, ADMINISTRATOR’)>: the roles are separated by a coma and the whole chain is enclosed in simple quotes

hasAnyRole(‘ADMINISTRATOR’,’DESIGNER’): the roles are enclosed first in simple quotes then separated by a coma

21 Comments

  1. Pingback: Spring MVC part VI: ThymeLeaf advanced usage « Yet Another Java Blog

  2. Pingback: Spring MVC part IV: ThymeLeaf advanced usage « Yet Another Java Blog

  3. Rafael

    Great blog entry. Thank you very much for this information¡

    Reply
    1. Rafael

      I edit for to say that in version 5.0:

      – It isnt necesary to create file springsecurity.taglib.xml
      – Maven dependencies are not correct in the principal website. The correct dependencies are:

      org.springframework.security
      facelets-taglib-jsf20-spring-3
      0.5

      – The name of methods have changed: areAllGranted is ifAllGranted,….. It is advisable to see javadoc for version 5.0.

      Kind regards.

      Reply
      1. DuyHai DOAN

        Thanks Rafael. By looking into the code again, I realized that what is in the article is not the code from http://www.dominikdorn.com/facelets/ but an extract of the spring-faces.jar from Spring Webflow. I just modify the article accordingly.

        Thank you

        Reply
      2. ouafae

        Hi , I use the same dependencies in my project ( facelets-taglib-jsf20-spring-3
        0.5 and spring-security) but I have problem when I use for example :

        i get an ERROR : Function ‘:ifAnyGranted’ not found, and if i use :
        my compenent

        it’s ingnored , my compenent is not hiding.

        Reply
  4. DuyHai DOAN

    @ouafae

    I have updated the article, you should use “areAnyGranted” instead of “ifAnyGranted”

    Reply
  5. Andrea (@elsarfhem)

    I’m not able to make it work… JSF 1.2 & spring 3.1, security 3.1 & webflow 2.3 library…
    Every sec tags are ignored or not found. I use the right springsecurity.taglib.xml for JSF 1.2 as stated in spring webflow configuration

    Reply
    1. DuyHai DOAN

      @Andrea

      Did you declare the taglib file in the web.xml as mentioned above ?

      javax.faces.FACELETS_LIBRARIES
      /WEB-INF/springsecurity.taglib.xml

      Can you put your code on GitHub or a public repo so I can have a look ?

      Reply
  6. Hong

    I can not make it work.

    I use JSF 2.1.7 and spring webflow, It seems that the stop working whenever I introduce the spring webflow, below is my maven dependency:

    org.springframework.webflow
    spring-faces
    2.3.1.RELEASE

    commons-logging
    commons-logging

    Reply
    1. DuyHai DOAN

      Hello Hong.
      What do you mean by “it stop working” ? Did you have some exception or stack trace in the logs ?

      Reply
  7. Richie

    Hello Hong
    Do you implement the Authentication tag in a similar way to the Authorization tag for jsf2 with facelets. Is there a FaceletsAuthenticationTagUtils that I have to setup in springsecurity.taglib.xml. I’m trying to display the principal.username

    Reply
    1. vijay

      Hi Richie,
      Any luck even i try to display principal.username in jsf, but no luck.

      Reply
  8. y

    great tip. thanks!

    Reply
    1. DuyHai DOAN

      Welcomed!

      Reply
  9. Leaon

    Why the tag in my page output nothing?

    Reply
    1. DuyHai DOAN

      WordPress is escaping some HTML characters I believe. You should enclose them in special characters to escape

      Reply
  10. Ilse

    Howdy! I could have sworn Ive been to this website before but after browsing through some of the post I realized its new to me.

    Anyhow, Im definitely happy I found it and Ill be
    book-marking and checking back frequently!

    Reply
    1. DuyHai DOAN

      Welcomed !

      Reply
  11. JP Villemin

    Nice tip. I’m actually facing a problem with JSF2 and Taglib security…I post on StackOverflow http://stackoverflow.com/questions/19387228/spring-security-taglib-authorize-authentication-are-not-working-with-role-hierar
    If you have some time to loose … : ) Thanks

    Reply
  12. Pingback: Spring Security 3.1.4 taglib authorize/authentication are not working with role hierarchy in JSF 2.1 | Technology & Programming Answers

Leave a Reply to DuyHai DOAN Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.