Spring Security with Maven

Spring Security is a powerful and highly customizable authentication access management system. This is standard for protecting Spring-based applications. Spring Security is a framework that focuses on authentication and authorization for Java applications.

Spring Security is a robust framework with breadth, designed to provide authentication and authorization capabilities for Java applications. Break down all the authentication, authorization, and security mechanisms provided by Spring Security.

1. Authentication

Authentication is the process of verifying that the user or system is human. It answers the question, “Who are you?” Spring Security supports several different authentication methods, including:

  • In-Memory Authentication: Useful for testing or very small applications where users and their roles can be defined in application memory.
  • JDBC Authentication: Uses the database to store user details and roles for the application.
  • LDAP Authentication: For applications needing authentication against Lightweight Directory Access Protocol (LDAP), such as Microsoft Active Directory or Spring applications.
  • OAuth2: For modern applications requiring integration with OAuth2 providers like Google, Facebook, GitHub, or other corporate authentication systems.
  • Custom Authentication Providers: For unique authentication needs not covered by the built-in providers of Spring Boot.

Spring Security authentication is managed through the AuthenticationManager interface, which has a single method called authenticate(). It can be composed of one or more AuthenticationProvider instances, each of which knows how to handle specific types of authentication.

2. Authorization

A license determines what actions an authenticated user is allowed to perform. It addresses the question, “What are you allowed to do?” This could be simple role checks like ROLE_USER or ROLE_ADMIN, or more complex access control logic in Spring applications.

Spring Security handles authorization at two levels:

  • Web Security: This involves configuring access to HTTP URLs. Spring Security provides options to restrict access based on URL patterns, HTTP methods, and authority checks.
  • Method Security: This protects service layer operations based on annotations such as @PreAuthorize, @PostAuthorize, @Secured, and @RolesAllowed. These annotations express security rules directly in business methods.

3.Protection Against Attacks

Spring Security offers various protections against common vulnerabilities:

  • Cross-Site Request Forgery (CSRF): It provides CSRF protection by default in web applications. It ensures that only forms originating from the application can be used to post data back.
  • Session Fixation: It prevents attackers from hijacking valid user sessions during the login process of the application.
  • Cross-Site Scripting (XSS): It can be handled by properly encoding data on the client side. Spring Security integrates with headers that instruct the browser to execute scripts only from trusted sources.
  • CORS: CORS stands for Cross-Origin Resource Sharing. Spring Security can be configured to control which domains are allowed to access the resources, which is essential for APIs consumed by different domain frontends.

4. Filter Chain

The filter chain is responsible for carrying out security processes. When a request is made, it goes through a series of filters, each designed to perform a specific task. Some critical filters include:

  • Authentication Filters: These filters authenticate the credentials submitted with requests.
  • Management Filters: These handle various aspects of the session and other security headers.
  • Access Control Filters: They decide if the request can proceed to the resources.

5. Configuration Models

Spring Security can be configured via XML or Java configurations. Java Configuration is type-safe, refactor-friendly, and more readable compared to XML.

Implementation of the Spring Security with Maven

Below are the steps to implement spring security with maven.

Step 1:

Create a new Spring Boot project using Spring Initializr and include the required dependencies,

Note: Choose Maven on creating the Spring project.

  • Spring Web
  • Spring Security
  • Lombok

Once the project is created, the file structure will resemble the image below.


Step 2:

Open the application.properties file and add the configuration for the security username and password of the Spring Security application in the project.

spring.application.name=spring-security-maven

spring.security.user.name=user
spring.security.user.password=user


Step 3: Create the Security Configuration class.

We can create the SecurityConfig class to configure Spring Security in the project. Go src > org.example.springsecuritymaven > SecurityConfig and put the below code.

Java
package org.example.springsecuritymaven;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic();
    }
}


Step 4: Create the Controller class.

We will create the HomeController class that will create the secure REST API of the spring project. Go src > org.example.springsecuritymaven > HomeController and put the below code.

Java
package org.example.springsecuritymaven;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {
    @GetMapping("/home")
    public String home() {
        return "Welcome to the secured site!";
    }
}


Step 5: Main Class(No Changes are required)

Go src > org.example.springsecuritymaven > SpringSecurityMavenApplication and put the below code.

Java
package org.example.springsecuritymaven;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringSecurityMavenApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringSecurityMavenApplication.class, args);
    }

}


Step 6: Run the Application

Now, we will run the application then it will be start port at 8080.


Step 7: Test the Application

Output:

http://localhost:8080/

It will redirect the below screen:


Enter the username: user and password : user then click sign in button there will the /home secure endpoint of the application.

http://localhost:8080/home

Output:

After hitting the URL in browser, we will get the below output.


This example demonstrates the Spring Security with Maven and configures the essential authentication and authorization aspects of the Spring Boot application.



Contact Us