What is Spring security

In this post of Spring security series, we will start with the introduction of Spring security. The goal of this post is to answer the basic question “What is Spring Security?” and why do we need it in our application.

 

1. Introduction

Web applications are susceptible to security threats and attacks, as they are accessible by anyone uses the internet. There may exist some REST endpoints having restricted access to specific users, for example, updating records or admin related operations. We can use spring security to secure URLs. Spring Security is a security framework that secures J2EE-based enterprise applications, by providing powerful, customizable security features like authentication and authorization. It is the de facto standard for securing Spring-based applications.

There are two major operations provided by Spring security, namely:

 

1.1.  Authentication

Used to verify if a user using an application by providing valid credentials used to verify who you are! Authentication is establishing identity of a principal (user, system, that can perform an action in an application).

 

1.2.  Authorization

Used to authorize a user before the user tries to access a resource. It is a process of access control, deciding whether it allows a principal to perform an action (access-control → admin, user, leader, manager, contractor, anonymous etc) or not.

 

2. Advantages of Spring security

Here are some important advantages of Spring Security:

  • Servlet API integration.
  • Spring MVC integration.
  • Portability.
  • Protection against CSRF attacks.
  • Java configuration support

To enable basic Spring security to J2EE applications, we follow the below 3 steps.

  1. Add jar files
  2. Filter declaration to pom.xml
  3. Java configuration by using SecurityConfiguration class

Let’s look at each step.

 

3. Spring Security Modules

In Spring Security 3.0, the Security module comprises separate jar files based on its functionality. The main use is to allow the user to integrate according to the requirements. To include minimal spring security for your Maven project, include below dependencies in your pom.xml.

  • Core – spring-security-core.jar–This module contains core authentication and access-control related classes, basic provisioning APIs. This is mandatory for providing spring security to any J2EE based enterprise application. This module supports non-web applications, too.
  • Web – spring-security-web.jar–This module contains filters and web-based authentication, like access control for URLs in a Servlet environment.
  • Config- spring-security-config.jar–This module used to use the Spring Security XML name-space.

 

3.1. Maven Setup

The minimum requirements to enable spring security is : Spring security 3.0 and jdk 1.5. or above versions.

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>4.1.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>4.1.2.RELEASE</version>
</dependency>

Always check the latest version on the Spring security before updating the pom.xml.

 

4. Adding Filter to web.xml

Add the below filter declaration to your pom.xml, to use the Spring Security web infrastructure:

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

We use filters to intercept every request in a J2EE application. DelegatingFilterProxy class in the package org.springframework.web.filter provided by the Spring framework to enable Spring security. Spring security is enabled by using URL filtering through DelegatingFilterProxy. In Spring, the filter classes are Spring beans that implements Filter interface, defined in the application context, making use of the dependency- injection features.

Spring Security maintains a security filter chain internally where filters we can add/remove from the configuration depending on the services required and each of the filters has a particular responsibility.

  • SecurityContextIntegrationFilter – Responsible to establish SecurityContext and maintaining it between HTTP requests.
  • LogoutFilter–Clears the SecurityContextHolder whenever we logout.
  • UsernamePasswordAuthenticationFilter–This filter is responsible to Authenticate to SecurityContext whenever we require login.
  • ExceptionTranslationFilter–Responsible for converting SpringSecurity exceptions to HTTP responses.
  • FilterSecurityInterceptor–This filter performs security handling of HTTP resources through filter implementation. This filter also allows requests based on authorities.

Based on the services requirements, we can add or replace filters, since each filter has a specific responsibility in the filter chain.

 

5. Java Configuration

We can configure spring security by editing web.xml or by extending the WebSecurityConfigurerAdapter implementation. In both the methods, we can define the providers for authentication and authorization and descriptions of application scopes that need authentication and/ or authorization. So, the user can specify what to secure and how to secure it. We can configure this in the SecurityConfiguration class.

Web SecurityConfiguration Adapter is the java configuration class for configuring web-based security, where all spring security related injection happens. You can override the methods of this class to provide access to url’s that need to be secure. We can add security to our app by including spring-boot-starter-security dependency on the classpath of our application.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

By adding the above dependency, by default all endpoints are secure. We can define custom Security config by creating a config class that extends WebSecurityConfigurerAdapter class. We use @EnableWebSecurity annotation to enable web security.

@Configuration
@EnableWebSecurity
public class SecurityJavaConfig extends WebSecurityConfigurerAdapter {
// ... }

 

6. Configuring HTTP Element

We need to begin with the <http> configuration, to enable web security.

<http auto-config='true'>
    <intercept-url pattern="/**" access="ROLE_USER" />
</http>

By configuring the http element in the above way, we can secure all URLs of our application and provide access to anyone has the role ROLE_USER. This defines a pattern for matching with URLs of the incoming requests. The ‘access’ attribute specifies the access requirements for requests that match the specified pattern. The “ROLE” prefix shows the user’s authorities.

By following the above steps, we will add basic spring security to our applications. The “auto-config” attribute automatically adds features like form-based login, basic authentication and log-out. Spring Security automatically generates login form by using default values for the URL that processes the login.We can also customize these features.

 

7. Spring Security Architecture

Spring security has an architecture to separate authentication from authorization and has strategies and extension points for both. The Authentication subsystem is responsible for validity of the client’s credentials. For example, username or password. Below is the Spring security architecture diagram.

Spring Security architecture

AuthenticationManager interface is responsible to provide authentication in Spring Security. The AuthenticationManager provides a useful method named authenticate() to achieve the authentication mechanism.

public interface AuthenticationManager {
  Authentication authenticate(Authentication authentication)
    throws AuthenticationException;
}

The login request from the client passed to the Authentication Filter, which passes the login credentials to the AuthorizationManager. If the input is a valid credential, the authenticate method returns “True”, the method throws an exception “AuthenticationException” if the input is an invalid principal and the method returns “Null” if the AuhorizationManager cannot decide if the input is valid or invalid.

The ProviderManager is the implementation of AuthenticationManager. The ProviderManager delegates a chain of AuthenticationProvider objects. The AuthentictionProvider is like the AuthenticationManager, except it has an extra method named support(). This method allows to query if the object supports an Authentication type.

public interface AuthenticationProvider {
    Authentication authenticate(Authentication authentication)
                   throws AuthenticationException;
    boolean supports(Class<?> authentication);
}

Once the authentication process is over, the Authorization mechanism starts.AccessAuthorizationManager interface is the core entity to provide Authentication mechanism and is responsible to make access control decisions. The AcessAuthorization manager provides a useful method named decide() to make the authorization decision based on information passed.

 

Summary

In this post we try to answer a basic question “What is spring security?” and why we need it. In this article we discussed the importance of Spring Security. We went through steps to configure basic Spring security for any J2EE-based application. Along with this, we also discussed the overall architecture of Spring Security. Hope this tutorial was informative.

Java Development Journal

Hello!! Welcome to the Java Development Journal. We love to share our knowledge with our readers and love to build a thriving community.

follow me on:

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of