Spring Security Authorize Tag Example

 

In Spring Security, the authorize tag is used to secure resources inside the JSP pages, like buttons, labels, links,..

In this example, we will add an HTML link to a JSP page and we will use the authorize tag to make this link visible only by users who have the required authority.

 

1. Technologies used

  • Spring Security 3.2.5.RELEASE
  • JSF 2.2.8
  • MySQL 5
  • Maven 3.0.5
  • Eclipse 4.4
  • JDK 1.7
  • Tomcat 7.0

 

2. Project structure

We will use Spring Security in a JSF 2 web application.

Spring Security Authorize Tag Example

 

3. Project dependencies

To use the authorize tag, we need to add the spring-faces dependency in the pom file :

 

4. Spring Security configuration

File : spring-security.xml

We have defined two hadcoded users : Walid and Khadija.

In addition to ROLE_USER, Khadija has also the ROLE_ADMIN authority.

 

5. Spring Security Taglib

To use the security tag library in our JSF application, we need to create the /WEB-INF/spring-security.taglib.xml with the following content :

It contains methods which can be used in the authorize tag.

 

6. web.xml

We need to register the spring-security.taglib.xml in the web.xml :

 

7. JSF pages

The login form : login.xhtml

 

We will use the authorize tag in the welcome page, so we need to declare the security tag, as shown below.

The homepage : welcome.xhtml

We have included the “Admin Page” link in the authorize tag, so that only users with the ROLE_ADMIN authority can see the HTML link.

 

The secured page : admin.xhtml

 

8. Test It

URL : localhost:8080/SpringSecurityAuthorizeTagExample/login.jsf

Log in with Walid credentials :

Spring Security Authorize Tag Example 1

Walid don’t have the ROLE_ADMIN authority, so he will not see the HTML link :

Spring Security Authorize Tag Example 2

Now, connect with Khadija credentials :

Spring Security Authorize Tag Example 3
Since Khadija has the ROLE_ADMIN authority, she can see the HTML link to access the admin page :

Spring Security Authorize Tag Example 4

Admin page :

Spring Security Authorize Tag Example 5

 

Download source code