Spring Security Hello World

In this tutorial, we will use Spring Security with a JSF application to secure a specific resource (JSF page).

We will implement an HTTP basic authentication to access the content of an index page by users having the right credentials.

 

1. Technologies used

  • Spring Security 3.2.5.RELEASE
  • JSF 2.2.8
  • Maven 3.0.5
  • Eclipse 4.2
  • JDK 1.6
  • Tomcat 7.0

 

2. Project structure

We create a JSF web application.

Spring-Security-Hello-World-1

 

3. Spring Security dependencies

To use Spring Security in our application, we need to add the three libraries : spring-security-core, spring-security-web and spring-security-config.

 

4. Spring Security configuration

File : spring-security.xml

We didn’t explicitly set an URL for the login page, so Spring Security will generates one automatically.

The intercept-url says only users with USER_ROLE role can access to index page.

We have defined a hardcoded  user (walid, 111, USER_ROLE) in the authentication-provider.

 

5. Web app Configuration

File : web.xml

To use Spring Security in our web application, we must add the filter  DelegatingFilterProxy.

DelegatingFilterProxy intercepts incoming requests and delegate them to springSecurityFilterChain for processing.

springSecurityFilterChain is a Spring bean created by the <http> element used in spring-security.xml, it maintains the chain of filters responsible for all the web security features.

springSecurityFilterChain implements javax.servlet.Filter.

 

6. JSF page

It is the page we have to secure.

File : index.xhtml

 

7. Test It

We will try to access : http://localhost:8080/Spring-Security-Hello-World/index.xhtml

So we will be redirected to login page (generated automatically by Spring Security).

Spring-Security-Hello-World-2

If we enter an incorrect username or password, we will get the error messages below :

Spring-Security-Hello-World-3

But if we enter the correct credentials, we can then access index page :

Spring-Security-Hello-World-4

 

Download source code