Spring Security Resources Access Control

In this example, we will use Spring Security to secure application resources so they can be accessed only by users with the required authorities. The resources, in our case, will be XHTML pages.

 

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.

SpringSecurityResourcesAccessControl

 

3. Project dependencies

We add the required dependencies in our project’s pom.xml :

 

4. JSF pages

Now, we create our XHTML pages, these are the application resources to secure.

login.xhtml : The login form. It must be accessible by everyone.

 

welcome.xhtml : The homepage. Accessible by users with the ROLE_USER authority.

 

admin.xhtml : accessible only by users having the ROLE_ADMIN authority.

 

5. Spring Security configuration

Here is how to configure access restrictions on our XHTML pages.

File : spring-security.xml

Khadija has access to all pages whereas Walid can only access the login page and welcome page.

Note that the pattern “/admin*” is less restrictive than the pattern “/admin.jsf“,  but in our case it means the same thing.

 

6. web.xml

 

7. Test It

URL : localhost:8080/SpringSecurityResourcesAccessControl/login.jsf

Log in using Walid credentials (Walid, 111)

SpringSecurityResourcesAccessControl-1

Walid has the required role to access the welcome page, but what will happen when “Walid” click the “Administration” link?

SpringSecurityResourcesAccessControl-2

Oops! Walid doesn’t have the required role to access the “admin” page.

SpringSecurityResourcesAccessControl-3

Now, connect using Khadija credentials (Khadija, 222)

Spring Security Authorize Tag Example 3

Khadija has ROLE_USER and ROLE_ADMIN. It means she can access both pages : “welcome” and “admin“.

Admin page :

SpringSecurityResourcesAccessControl-6

Download source code