Spring Security Example Tutorial

Spring Security provides ways to perform authentication and authorization in a web application. We can use spring security in any servlet based web application.

Spring Security

Some of the benefits of using Spring Security are:

  1. Proven technology, it’s better to use this than reinvent the wheel. Security is something where we need to take extra care, otherwise our application will be vulnerable for attackers.
  2. Prevents some of the common attacks such as CSRF, session fixation attacks.
  3. Easy to integrate in any web application. We don’t need to modify web application configurations, spring automatically injects security filters to the web application.
  4. Provides support for authentication by different ways – in-memory, DAO, JDBC, LDAP and many more.
  5. Provides option to ignore specific URL patterns, good for serving static HTML, image files.
  6. Support for groups and roles.

Spring Security Example

We will create a web application and integrate it with Spring Security.

Create a web application using “Dynamic Web Project” option in Eclipse, so that our skeleton web application is ready. Make sure to convert it to maven project because we are using Maven for build and deployment. If you are unfamiliar with these steps, please refer Java Web Application Tutorial.

Once we will have our application secured, final project structure will look like below image.

Spring-Security-ignore

We will look into three spring security authentication methods.

  1. in-memory
  2. DAO
  3. JDBC

For JDBC, I am using MySQL database and have following script executed to create the user details tables.

We would also need to configure JDBC DataSource as JNDI in our servlet container, to learn about this please read Tomcat JNDI DataSource Example.

Spring Security Maven Dependencies

Here is our final pom.xml file.

We have following dependencies related to Spring Framework.

  1. spring-jdbc: This is used for JDBC operations by JDBC authentication method. It requires DataSource setup as JNDI. For complete example of it’s usage, please refer Spring DataSource JNDI Example
  2. spring-security-taglibs: Spring Security tag library, I have used it to display user roles in the JSP page. Most of the times, you won’t need it though.
  3. spring-security-config: It is used for configuring the authentication providers, whether to use JDBC, DAO, LDAP etc.
  4. spring-security-web: This component integrates the Spring Security to the Servlet API. We need it to plugin our security configuration in web application.

Also note that we will be using Servlet API 3.0 feature to add listener and filters through programmatically, that’s why servlet api version in dependencies should be 3.0 or higher.

Spring Security Example View Pages

We have JSP and HTML pages in our application. We want to apply authentication in all the pages other than HTML pages.

health.html

index.jsp

I have included index.jsp as welcome-file in the application deployment descriptor.

Spring Security takes care of CSRF attack, so when we are submitting form for logout, we are sending the CSRF token back to server to delete it. The CSRF object set by Spring Security component is _csrf and we are using it’s property name and token value to pass along in the logout request.

Let’s look at the Spring Security configurations now.

Spring Security Example UserDetailsService DAO Implementation

Since we will be using DAO based authentication also, we need to implement UserDetailsService interface and provide the implementation for loadUserByUsername() method.

Ideally we should be using some resource to validate the user, but for simplicity I am just doing basic validation.

AppUserDetailsServiceDAO.java

Notice that I am creating anonymous inner class of UserDetails and returning it. You can create an implementation class for it and then instantiate and return it. Usually that is the way to go in actual applications.

Spring Security Example WebSecurityConfigurer implementation

We can implement WebSecurityConfigurer interface or we can extend the base implementation class WebSecurityConfigurerAdapter and override the methods.

SecurityConfig.java

Notice that we are ignoring all HTML files by overriding configure(WebSecurity web) method.

The code shows how to plugin JDBC authentication. We need to configure it by providing DataSource. Since we are using custom tables, we are also required to provide the select queries to get the user details and it’s roles.

Configuring in-memory and DAO based authentication is easy, they are commented in above code. You can uncomment them to use them, make sure to have only one configuration at a time.

@Configuration and @EnableWebSecurity annotations are required, so that spring framework know that this class will be used for spring security configuration.

Spring Security Configuration is using Builder Pattern and based on the authenticate method, some of the methods won’t be available later on. For example, auth.userDetailsService() returns the instance of UserDetailsService and then we can’t have any other options, such as we can’t set DataSource after it.

Integrating Spring Security Web with Servlet API

The last part is to integrate our Spring Security configuration class to the Servlet API. This can be done easily by extending AbstractSecurityWebApplicationInitializer class and passing the Security configuration class in the super class constructor.

SecurityWebApplicationInitializer.java

When our context startup, it uses ServletContext to add ContextLoaderListener listener and register our configuration class as Servlet Filter.

Note that this will work only in Servlet-3 complaint servlet containers. So if you are using Apache Tomcat, make sure it’s version is 7.0 or higher.

Our project is ready, just deploy it in your favorite servlet container. I am using Apache Tomcat-7 for running this application.

Below images show the response in various scenarios.

Accessing HTML Page without Security

Spring-Security-ignore

Authentication Failed for Bad Credentials

Spring-Security-ignore

Home Page with Spring Security JDBC Authentication

Spring-Security-ignore

Home Page with Spring Security UserDetailsService DAO Authentication

Spring-Security-ignore

Home Page with Spring Security In-Memory Authentication

Spring Security Example In Memory

Logout Page

Spring Security Form Logout

If you want to use Servlet Container that doesn’t support Servlet Specs 3, then you would need to register DispatcherServlet through deployment descriptor. See JavaDoc of WebApplicationInitializer for more details.

That’s all for Spring Security example tutorial and it’s integration in Servlet Based Web Application. Please download the sample project from below link and play around with it to learn more.

By admin

Leave a Reply

%d bloggers like this: