Implementation of Spring Security – CORS
This project demonstrates how to implement Cross-Origin Resource Sharing (CORS) in a Spring Boot application with Spring Security. The goal is to configure CORS headers to control which domains can access the application’s resources while ensuring security.
Step 1: Create the Spring project
Create the new Spring Boot project using Spring Initializr and add the required dependencies,
- Spring Web
- Spring Security
- Lombok
- Spring DevTools
Once the project is created then the file structure will resemble the image below.
Step 2: Configure the application properties
Open the application.properties file and add the configuration for the spring security username and password of the application in the project.
spring.application.name=spring-security-cors
spring.security.user.name=user
spring.security.user.password=password
Step 3: Configure the Security Configuration class.
We will create the SecurityConfig class to configure Spring Security in the project. Go src > org.example.springsecuritycors > SecurityConfig and put the below code.
package org.example.springsecuritycors;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin();
return http.build();
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://localhost:8080");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
Spring security can be implemented the integrate the CORS configuration with the Spring Security using the SecurityFilterChain of the Spring application.
- addMapping(“/**”): It can applies the CORS configuration to all the endpoints of the application.
- allowedOrigins(“http://example.com”): It can allows the requests only from http://example.com of the application.
- allowedMethods(“GET”, “POST”,”PUT”, “DELETE”): It can allows these http methods only of the Spring application.
- allowedHeaders(“*”): It can allows all the headers of the application.
- allowCredentials(true): It can allows the cookies and other credentials to be included.
- maxAge(3600): It can sets the maximum age of the CORS preflight request cache of the application.
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.springsecuritycors > HomeController and put the below code.
package org.example.springsecuritycors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, CORS!";
}
}
Step 5: Main Class
No changes are required in the main class of the project.
package org.example.springsecuritycors;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringSecurityCorsApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSecurityCorsApplication.class, args);
}
}
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.example</groupId>
<artifactId>spring-security-cors</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-security-cors</name>
<description>spring-security-cors</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 6: Run the Application
Now, we will run the application and then it will start at port 8080.
login Endpoint:
Endpoint Testing:
Step 7: Testing the Cross-Origin Request
- We can use the tool like the front-end application hosted on the http://example.com to make the GET request to the http://localhost:8080/hello.
- It ensures the request is successful and the response is “Hello, CORS!”.
These steps ensures that the application can handle cross-origin requests securely, improving both security and user experience.
Spring Security – CORS
Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers to allow or block web pages from making requests to a different domain than the one that served the web page. It plays a crucial role in preventing certain types of attacks, such as Cross-Site Request Forgery (CSRF). By default, web browsers block cross-origin HTTP requests from scripts running in the browser. CORS provides a way for servers to support cross-origin requests while still ensuring the security of the application.