Spring Security Example UserDetailsService

Welcome to Spring Security Example using UserDetailsService. In the last post we learned how to use Spring Security in Web Application. Today we will look into how we can integrate Spring Security in Spring MVC Projects for authentication purposes.

Spring Security Example

Integrating Spring Security with Spring MVC Framework is very easy, because we already have Spring Beans configuration file. All we need is to create spring security authentication related changes to get it working. Today we will look into how we can implement authentication in Spring MVC application using in-memory, UserDetailsService DAO implementation and JDBC based authentication.

First create a simple Spring MVC project in the Spring Tool Suite, that will give us the base spring MVC application to build our Spring security example application. Once we will be done with all the changes, our application will look like below image.

Spring-MVC-Security-Project1

Let’s look into each of the components of our Spring security example project.

Spring Security Maven Dependencies

Our final pom.xml file looks like below.

We have included spring-security-config and spring-security-web dependencies for Spring Security. Apart from that we have spring-jdbc dependency because we will be using Spring JDBC authentication too.

Rest of the dependencies are related to Spring MVC, logging, AOP etc.

Spring Security Example Deployment Descriptor

Our web.xml file looks like below.

contextConfigLocation is the context parameter where we provide the spring security beans configuration file name. It is used by ContextLoaderListener to configure authentication in our application.

We have also added HttpSessionEventPublisher listener to publish session created/destroyed events to the Spring Root WebApplicationContext.

I am also setting session-timeout to 15 minutes, this is used for auto timeout when user is inactive for 15 minutes.

DelegatingFilterProxy is the application filter defined, it is used for intercepting the HTTP requests and performing authentication related tasks.

DispatcherServlet servlet is the front controller for the Spring MVC application.

UserDetailsService

If we want to use any DAO class for authentication, we need to implement UserDetailsService interface. Once the DAO is configured, it’s loadUserByUsername() is used to validate the user.

Note that I am returning UserDetails instance by using anonymous inner class implementation. Ideally, we should have an implementation class for UserDetails that can have other user data also, such as emailID, user name, address etc.

Notice that the only combination that will work is when user name is “pankaj” and password is “pankaj123”.

Spring Security Example Controller Class

Here is our controller class that defines two URIs that we can access.

In our example, we will apply authentication to URI “/emp/get/{id}” only. All other URIs will be accessible without any authentication. login, logout and denied URIs are used to send corresponding response pages when secured URL is requested.

Spring Security Example Bean Configuration File

Our spring bean configuration file is simple, it has configurations related to Spring MVC application only.

Spring MVC Security Configuration

This is the most important part of our tutorial, let’s have a look at our file. We will understand each of the parts one by one.

spring-security.xml

accessDecisionManager bean is defined so that we can have our custom roles, by default all the roles should start with ROLE_ and we are overriding this setting in the roleVoter bean property rolePrefix.

We can have multiple authentication managers defined in the spring security configuration. I have defined in-memory-auth for in-memory authentication, dao-auth for UserDetailsService DAO implementation and jdbc-auth for JDBC authentication. For JDBC authentication, I have provided configuration for DataSource defined in the application as well as if we want to use JNDI resource defined in the servlet container.

http authentication-manager-ref is used to define the authentication manager that will be used for authenticating the user. Currently it’s configured to use the JDBC based authentication.

http access-decision-manager-ref is used to specifying the ID of the AccessDecisionManager implementation which should be used for authorizing HTTP requests.

intercept-url is used to define the URL pattern and authorities of the user who can access this page. For example, we have defined that URI “/emp/**” can be accessible only by users having “Admin” access.

form-login defines the login form configuration and we can provide the username and password parameter names. authentication-failure-url is used to define the URL for the authentication failure page. If no login failure URL is specified, Spring Security will automatically create a failure login URL at /spring_security_login?login_error and a corresponding filter to render that login failure URL when requested.

default-target-url is used to define the default URL that will be redirected to after successful authentication, if the user’s previous action could not be resumed. This generally happens if the user visits a login page without having first requested a secured operation that triggers authentication. If unspecified, it defaults to the root of the application.

logout is used to define the logout processing filter. Here we are invalidating the session and sending the user to login page after successful logout. logout-url is used to define the URL to be used for logout action.

access-denied-handler defines the global error page if the user is denied the access, because he is not authorized to perform the specified action.

session-management will add a SessionManagementFilter filter to the filter stack for Session Management.

There are some other configurations also, but I have included most of the important ones that we use.

Spring Security Example View Pages

Let’s have a quick look at our view pages, before we deploy and test our application.

home.jsp

home.jsp is returned for “/home” URI and it should not require any authentication.

employee.jsp

This page is returned when we are accessing URI that requires authentication. Here I have provided logout option so that user can logout and terminate the session. Once logout is successful, user should be sent back to login page as configured.

login.jsp

There are few important points to note here. The first one is that the login URL is “/j_spring_security_check“. This is the default login processing URL, just like the logout-url.

Another important point is the form parameters name for username and password. They should be same as configured in the spring security configurations.

logout.jsp

denied.jsp

logout.jsp and denied.jsp pages are simple, but we could have included some information here based on the user details.

Our spring security example application is ready to test, note that for JDBC authentication I am using the same setup as our previous Spring Security Example. So if you have landed directly here, you should check that out.

Spring Security MVC Example Testing

Just deploy the application in your favorite servlet container, mine is Apache Tomcat 7. Below images show us the different outputs for different URLs.

Spring Security Example – Home Page without Authentication

spring-mvc-permitAll

 

Spring Security Example – Login Page when Authentication Enabled Page is requested (/emp/get/{20})

spring-mvc-permitAll

Spring Security Example – Response Page when Authentication is Successful

Spring-MVC-Security-Project1

Spring Security Example – Access Denied Page when Authentication is Failed

Spring-MVC-Security-Project1

That’s all for the Spring Security Example using UserDetailsService, please download the sample project from below link and explore it to learn more.

By admin

Leave a Reply