Spring Security Form based Authentication – XML Configuration

In this tutorial I will show you the way to configure Spring Security with Spring MVC web application to secure pages. I will create spring mvc based web application and I will configure Spring Security to protect a page from outside access.

You may also like annotation based example Spring Security Form based Authentication – Annotations

Spring Security allows to you to integrate security features with JEE web application easily, it takes care about all incoming HTTP requests via servlet filter, and implements “user defined” security checking.

In this tutorial, I will show you how to integrate Spring Security 4.2.1 with Spring MVC4 web application to secure URL access.
For this tutorial I will create maven based web project in Eclipse.

Prerequisites

The following configurations are required in order to run the application

Eclipse Kepler
JDK 1.8
Tomcat 8
Have maven 3 installed and configured
Spring mvc 4 dependencies in pom.xml
Spring security 4 dependencies in pom.xml

Now we will see the below steps how to create a maven based project in Eclipse

Step 1. Create a maven based web project in Eclipse

Go to File -> New -> Other. On popup window under Maven select Maven Project. Then click on Next. Select the workspace location – either default or browse the location. Click on Next. Now in next window select the row as highlighted from the below list of archtypes and click on Next button.

maven-arctype-webapp

Now enter the required fields (Group Id, Artifact Id) as shown below

Group Id : com.roytuts
Artifact Id : spring-security

Step 2. Modify the pom.xml file as shown below.

The minimal dependency artifacts required for Spring Security are spring-security-web and spring-security-config.

Step 3. If you see JRE System Library[J2SE-1.5] then change the version by below process

Do right-click on the project and go to Build -> Configure build path, under Libraries tab click on JRE System Library[J2SE-1.5], click on Edit button and select the appropriate jdk 1.8 from the next window. Click on Finish then Ok.

Step 4. Now when the build process finished then modify the web.xml file with below source code

In web.xml, the first thing is to add the filter declaration DelegatingFilterProxy to your web.xml file as shown above.

This provides a hook into the Spring Security web infrastructure. DelegatingFilterProxy is a Spring Framework class which delegates to a filter implementation which is defined as a Spring bean in your application context. In this case, the bean is named springSecurityFilterChain, which is an internal infrastructure bean created by the namespace to handle web security. Note that you should not use this bean name yourself. Once you’ve added this to your web.xml, you’re ready to start editing your application context file. Web security services are configured using the <http> element.

I have also declared Spring MVC DispatcherServlet, that acts as a front controller, as shown above in the web.xml file to handle incoming request and response for the URL pattern "/".

Step 5. Create security.xml file under src/main/resources directory with the below source code

Security Namespace Configuration

A namespace element can be used simply to allow a more concise way of configuring an individual bean or, more powerfully, to define an alternative configuration syntax which more closely matches the problem domain and hides the underlying complexity from the user. A simple element may conceal the fact that multiple beans and processing steps are being added to the application context.

Design of the Namespace – xmlns:security

Web/HTTP Security – the most complex part. Sets up the filters and related service beans used to apply the framework authentication mechanisms, to secure URLs, render login and error pages and much more.
Business Object (Method) Security – options for securing the service layer.
AuthenticationManager – handles authentication requests from other parts of the framework.
AccessDecisionManager – provides access decisions for web and method security. A default one will be registered, but you can also choose to use a custom one, declared using normal Spring bean syntax.
AuthenticationProviders – mechanisms against which the authentication manager authenticates users. The namespace provides supports for several standard options and also a means of adding custom beans declared using a traditional syntax.
UserDetailsService – closely related to authentication providers, but often also required by other beans.

<security:http/> enables the web security. <security:http> element is the parent for all web-related namespace functionality. The <security:intercept-url> element defines a pattern which is matched against the URLs of incoming requests using an ant path style syntax. The access attribute defines the access requirements for requests matching the given pattern.

In the above configuration we want URL that has pattern /admin within our application to be secured, requiring the role ROLE_ADMIN to access them, we want to log in to the application using a custom login form with username and password, and that we want a logout URL registered which will allow us to log out of the application.

If you do not want to use custom login form then you can simply use <security:form-login/> to get the Spring’s default login form.

To add a user, for example in our case the username is roy, you need to use <security:authentication-manager/>. The <security:authentication-provider> element creates a DaoAuthenticationProvider bean and the <security:user-service> element creates an InMemoryDaoImpl. All authentication-provider elements must be children of the <security:authentication-manager> element, which creates a ProviderManager and registers the authentication providers with it. The configuration above defines one user, its password and its role within the application (which will be used for access control). It is also possible to load user information from a standard properties file using the properties attribute on user-service.

Step 6. Create controllers.xml file under src/main/resources directory with the below source code

I have configured <mvc:annotation-driven /> to work with annotations in Spring MVC.

I have also configured <mvc:resources location="/static/" mapping="/static/**" /> to load static resources from static directory.

I have configured <context:component-scan/> to load all annotation-driven controllers from the given base package.

I have also declared view resolver bean and message resource for i18n supports.

Step 7. Create below messages.properties file with below content and put it under src/main/resources folder

Step 8. Create below controller with below source

Step 9. We need some style, so create the below style.css file and put it under webapp/static/css directory

Step 10. Below is the index.jsp file and put it under webapp directory and see how keys are used to fetch corresponding value from messages.properties file. This index.jsp file is not secured and is accessible directly.

Step 11. Below admin.jsp file in webapp directory is secured and user must login before viewing the content of this file. When you try to access the admin.jsp file then you will automatically be redirected to the login.jsp file.

Step 12. The content of the login.jsp file under webapp directory.

Step 13. When you deploy the application and run the application you will see different output in the browser.

When you hit the URL http://localhost:8080/spring-security/


spring security

When you click on link Go to Administrator page


spring security

When you click on Submit button without giving any credentials or wrong credentials


spring security

When you give username/password as roy/roy


spring security

When you click on Logout link


spring security

Thanks for reading.

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.