Search Tutorials

Simple Spring Security example-Basic Authentication Provider | JavaInUse

Simple Spring Security example using Basic Authentication Provider

Quite a few times we require to authenticate a user for accessing pages developed using Spring MVC. This authentication can be achieved in number of ways. One way is to use web.xml security where roles are defined. However some part of this security implementation depends on the application server used. For example Tomcat checks to see that the sent username and password match a user entry in tomcat-users.xml. Thus according to the application server used, the changes would have to be done. Also only if one application server is to be used, still for each instance of the application server these changes would have to be done. Using Spring Security Authentication this is not the case. As spring security is part of the war file, it is independent of the application server.
For illustrating this will use this Simple MVC project. This project displays a list of employees when the URL- is hit. If you try to hit this url that is protected and you are currently unauthenticated, a popup window appears and you enter a particular username/password.

Lets Begin-

Our project will be as follows-

To the pom.xml add the spring security dependencies-
		<project xmlns="" xmlns:xsi=""
	<name>employee-management-system Maven Webapp</name>



In the security-config.xml we specify the url to be intercepted. We can instruct it to intercept all urls. Currently we have only intercepted the / Also for authentication currently we have hardcoded existing users and roles. We use user-service to define in memory usernames and roles as follows-
<beans:beans xmlns="" 
	<http auto-config="true" use-expressions="true">		
		<intercept-url pattern="/" access="hasRole('ROLE_USER')"/>
				<user name="javainuse" password="password" authorities="ROLE_USER,ROLE_ADMIN"/>
				<user name="test" password="password" authorities="ROLE_USER"/> 


In the web.xml we add the DelegatingFilterProxy which is delegating proxy to automatically intercept a URL with a particular pattern to apply spring security. Currently all urls are going to be intercepted by this filter.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="" xmlns:xsi=""

	<!-- Configure the Disptcher Servlet -->
	<!-- Filter the incoming requests for the .do pattern -->

		<param-value>/WEB-INF/Dispatcher-servlet.xml, /WEB-INF/security-config.xml</param-value>
	<!-- Spring Security -->

Now deploy the application on Tomcat-
. http://localhost:8080/employee-management-system/
As only the user having role ROLE_USER can visit this page, enter the credentials
username -javainuse and password-password or
username-test and password-password.

Download Source Code

Download it - Simple Spring Security example using Basic Authentication Provider