Prerequisites and Project Setup
To get started with **Spring Security** and **CORS** configuration, you’ll need to have a basic understanding of **Spring Boot** and its project structure. The required dependencies include **spring-boot-starter-security** and **spring-boot-starter-web**. You can add these dependencies to your **pom.xml** file if you’re using Maven.
The project structure should include a **config** package for security configurations, a **controller** package for handling HTTP requests, and a **model** package for data models. For a basic setup, you can create a **SecurityConfig** class that extends **WebSecurityConfigurerAdapter**.
For further reading on Spring Boot basics, you can visit our previous tutorial.
The **SecurityConfig** class will be used to configure **CORS** and other security settings. Here’s an example implementation:
package com.example.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// We're allowing CORS requests from any origin
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.anyRequest()
.permitAll();
}
}
When you run the application with this configuration, you should see no errors related to **CORS** or security. You can test this by sending a request to your application from a different origin. The expected output will be a successful response without any **CORS**-related errors.
HTTP/1.1 200 OK Content-Type: application/json
For more information on configuring CORS with Spring Security, you can refer to our detailed guide.
Understanding CORS and Spring Security
CORS, or Cross-Origin Resource Sharing, is a security feature implemented in web browsers to prevent web pages from making requests to a different origin (domain, protocol, or port) than the one the web page was loaded from. This is a critical security feature as it helps prevent malicious scripts from making unauthorized requests on behalf of the user. The HttpServletResponse object is used to set the necessary headers for CORS. For more information on CORS configuration, refer to our article on Configuring CORS in Spring Boot.
Table of Contents
- Prerequisites and Project Setup
- Understanding CORS and Spring Security
- Step-by-Step Configuration of CORS with Spring Security
- Full Example of CORS Configuration with Spring Boot
- Common Mistakes and Troubleshooting
- Mistake 1: Incorrect Filter Order
- Mistake 2: Missing Allowed Origins
- Mistake 3: Incorrect HTTP Methods
- Production-Ready Tips for CORS Configuration
- Testing and Validating CORS Configuration
- Key Takeaways and Conclusion
- Advanced Scenarios and Customization
When using Spring Security in a Spring Boot application, CORS needs to be configured to allow requests from different origins. This can be done by adding the CorsConfiguration to the HttpSecurity configuration. The CorsConfiguration allows you to specify the allowed origins, methods, and headers. By default, Spring Security will disable CORS, so it needs to be explicitly enabled.
The CORS configuration can be customized to fit the needs of the application. For example, you can specify the allowed origins using the setAllowedOrigins method, or specify the allowed methods using the setAllowedMethods method. You can also specify the allowed headers using the setAllowedHeaders method. The CorsConfiguration can be added to the HttpSecurity configuration using the cors method.
When configuring Spring Security with CORS, it is essential to understand the order of the filters in the Spring Security filter chain. The CorsWebFilter should be placed before the UsernamePasswordAuthenticationFilter to ensure that CORS requests are handled correctly. For more information on the Spring Security filter chain, refer to our article on Understanding the Spring Security Filter Chain.
Step-by-Step Configuration of CORS with Spring Security
To configure **CORS** (Cross-Origin Resource Sharing) with **Spring Security** in a **Spring Boot** application, you need to create a custom WebSecurityConfigurerAdapter class. This class will override the default security configuration to include CORS settings. Before proceeding, ensure you have a basic understanding of **Spring Boot Security** and have set up a Spring Boot Security project.
The first step is to create a new configuration class that extends WebSecurityConfigurerAdapter. In this class, you will override the configure method to add CORS configuration. You can use the CorsConfiguration class to define the allowed origins, methods, and headers.
To enable CORS for all endpoints, you can use the CorsRegistry class. This class provides a simple way to configure CORS settings for your application.
package com.example.security.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// Enable CORS for all endpoints
http.cors().and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
The expected output will be that your application now allows CORS requests from any origin. You can verify this by sending a request to your application from a different origin and checking the response headers for the Access-Control-Allow-Origin header.
HTTP/1.1 200 OK Access-Control-Allow-Origin: *
For further reading on **Spring Boot Security**, you can refer to our Spring Boot Security best practices article.
Full Example of CORS Configuration with Spring Boot
To configure **CORS** (Cross-Origin Resource Sharing) in a **Spring Boot** application, you need to create a **WebSecurityConfigurerAdapter** class that extends the WebSecurityConfigurerAdapter class. This class will override the configure method to add **CORS** configuration. For more information on **Spring Security**, you can visit our Spring Security tutorial.
The configure method will add a CorsConfigurationSource to the **HTTP** security configuration. This source will define the allowed origins, methods, and headers for **CORS** requests.
The following example demonstrates how to configure **CORS** in a **Spring Boot** application:
package com.example.springsecuritycors;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// Enable CORS
http.cors()
.and()
// Disable CSRF (cross site request forgery)
.csrf().disable();
// Allow all requests
http.authorizeRequests().anyRequest().permitAll();
}
// Create an in-memory user details manager
@Bean
public UserDetailsService userDetailsService() {
// Create a user with the username "user" and password "password"
User.UserBuilder users = User.withDefaultPasswordEncoder();
User user = users.username("user").password("password").roles("USER").build();
// Create an in-memory user details manager with the user
return new InMemoryUserDetailsManager(Arrays.asList(user));
}
}
The expected output of this configuration will be that all **CORS** requests are allowed, and all requests are permitted without authentication.
HTTP/1.1 200 OK Content-Type: application/json
For further reading on **Spring Boot** and **CORS** configuration, you can visit our Spring Boot tutorial and learn more about CORS configuration with CORS configuration.
Common Mistakes and Troubleshooting
When configuring **CORS** with **Spring Security** and **Spring Boot**, developers often encounter issues that can be tricky to resolve. One common mistake is misconfiguring the CORS filter.
To learn more about the basics of **Spring Security**, visit our Spring Security tutorial for a comprehensive introduction.
Mistake 1: Incorrect Filter Order
A common issue is placing the **CORS** filter after the **Spring Security** filter. This can lead to **CORS** requests being blocked by **Spring Security**.
The following code demonstrates the incorrect configuration:
// WRONG
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class) // WRONG - should be before Spring Security filter
.authorizeRequests()
.anyRequest().authenticated();
}
}
This configuration will result in a **403 Forbidden** error for **CORS** requests.
Mistake 2: Missing Allowed Origins
Another mistake is not specifying the allowed origins for **CORS** requests.
The correct configuration should include the allowed origins:
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class)
.authorizeRequests()
.anyRequest().authenticated();
}
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*"); // allow all origins
config.addAllowedHeader("*");
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
For more information on **Spring Boot** configuration, visit our Spring Boot configuration guide.
Mistake 3: Incorrect HTTP Methods
A common mistake is not allowing the correct **HTTP** methods for **CORS** requests.
The following code demonstrates the correct configuration:
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class)
.authorizeRequests()
.anyRequest().authenticated();
}
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*"); // allow all origins
config.addAllowedHeader("*");
config.addAllowedMethod("GET"); // allow only GET method
config.addAllowedMethod("POST"); //
Production-Ready Tips for CORS Configuration
When deploying a CORS configuration in a production environment, it is essential to consider security and performance. TheWebSecurityConfigurerAdapter class provides a convenient way to configure Spring Security settings, including CORS. To ensure proper CORS configuration, review the Spring Security tutorial for a comprehensive understanding of the framework.
Production tip: Configure theThe CORS configuration should be tested thoroughly to ensure it works as expected. This includes testing different HTTP methods, such ascorsmethod in theHttpSecurityconfiguration to allow only necessary HTTP methods and origins to prevent unauthorized access.
GET, POST, and PUT, as well as various origins and headers. For more information on HTTP methods, refer to the HTTP methods explained article.
Production tip: Use the CorsRegistry class to configure CORS settings globally, allowing for more flexibility and maintainability in the application.
To further enhance security, consider implementing additional measures, such as CSRF protection and SSL/TLS encryption. These features can be easily integrated into the application using Spring Security and Spring Boot. For more information on CSRF protection, visit the CSRF protection with Spring Security article.
Production tip: Monitor the application's logs and performance metrics to identify potential issues with the CORS configuration and make adjustments as needed.
Testing and Validating CORS Configuration
To ensure that **CORS** (Cross-Origin Resource Sharing) configuration is working as expected in a **Spring Boot** application, it's essential to test and validate the setup. One way to achieve this is by using tools like **Postman** or writing custom tests using **JUnit**. For instance, you can create a test class that sends a request to a protected endpoint and verifies the response headers. TheCorsConfiguration class in **Spring Security** provides various options to customize the CORS configuration, such as allowed origins, methods, and headers. To test these configurations, you can write a test class that extends the AbstractTestNGSpringContextTests class.
For more information on setting up **Spring Security** in your application, refer to our article on configuring Spring Security with Spring Boot.
Here's an example of a test class that verifies the CORS configuration:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
public class CorsConfigurationTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testCorsConfiguration() throws Exception {
// Send a request to a protected endpoint
mockMvc.perform(MockMvcRequestBuilders.options("/protected-endpoint"))
// Verify the response headers
.andExpect(status().isOk())
.andExpect(header().string("Access-Control-Allow-Origin", "*"));
}
}
The expected output of this test should indicate that the request was successful and the response headers contain the expected **CORS** configuration:
MockHttpServletRequest:
HTTP Method = OPTIONS
Request URI = /protected-endpoint
Parameters = {}
Headers = [Accept:*/*, Accept-Encoding:gzip, deflate, br, ...]
Body = null
Session Attrs = {}
Handler:
Type = org.springframework.web.servlet.handler.HandlerMethod
Method = public org.springframework.http.ResponseEntity<?> com.example.MyController.myMethod(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Access-Control-Allow-Origin:[*], Vary:[Origin], ...]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
By writing such tests, you can ensure that your **CORS** configuration is working correctly and that your application is secure. For further reading on **Spring Boot** testing, visit our article on testing Spring Boot applications.
Key Takeaways and Conclusion
When configuring **CORS** with **Spring Security**, it is essential to understand the role of the HttpSecurity configuration class. This class provides a builder API for customizing the **Spring Security** configuration, including **CORS** settings. By using the cors() method, developers can enable **CORS** support and define allowed origins, methods, and headers. For more information on **Spring Security** configuration, refer to our Spring Security Configuration tutorial.
The WebSecurityConfigurerAdapter class plays a crucial role in **Spring Security** configuration, including **CORS** setup. By extending this class, developers can override the configure(HttpSecurity http) method to customize the **Spring Security** configuration. This method is used to define the **CORS** configuration, including the allowed origins, methods, and headers. Understanding the filter chain is also essential when working with **Spring Security** and **CORS**.
When implementing **CORS** configuration with **Spring Security**, it is essential to consider the security implications of allowing cross-origin requests. Developers should carefully evaluate the allowed origins, methods, and headers to ensure that the **CORS** configuration does not introduce any security vulnerabilities. By following best practices and using the cors() method, developers can ensure a secure and functional **CORS** configuration. For further reading on Spring Boot security, visit our Spring Boot Security tutorial.
In conclusion, configuring **CORS** with **Spring Security** requires a thorough understanding of the HttpSecurity configuration class and the filter chain. By using the cors() method and following best practices, developers can ensure a secure and functional **CORS** configuration. For a comprehensive overview of **Spring Boot** and **Spring Security**, including **CORS** configuration, refer to our Spring Boot Tutorial and Spring Security Tutorial.
Advanced Scenarios and Customization
When dealing with complex **CORS** configurations, you may need to handle multiple origins, methods, and headers. To achieve this, you can use the WebMvcConfigurer interface to customize the CORS configuration. This can be done by overriding the addCorsMappings method and adding custom CorsRegistration instances.
To handle multiple origins, you can use the allowedOrigins method and pass in an array of allowed origins. For example, you can allow requests from both http://example1.com and http://example2.com by using the allowedOrigins method with an array of these two origins. Additionally, you can customize the allowed methods and headers using the allowedMethods and allowedHeaders methods.
For more information on customizing **Spring Security** configurations, you can refer to our article on Customizing Spring Security Configurations. This article provides an in-depth look at how to customize various aspects of **Spring Security**, including authentication and authorization. When customizing **CORS** configurations, it is essential to ensure that the configuration is properly secured to prevent unauthorized access.
To further customize the CORS configuration, you can use the CorsConfiguration class to create a custom configuration. This class provides various methods for customizing the **CORS** configuration, such as setting the maximum age of the **CORS** configuration and specifying the allowed origins, methods, and headers. By using these customization options, you can create a **CORS** configuration that meets the specific needs of your application.
spring-security-examples — Clone, Star & Contribute

Leave a Reply