![]() |
VOOZH | about |
CORS (Cross-Origin Resource Sharing) is a security feature that prevents web applications from making requests to a different domain without permission. When a frontend application (e.g., http://localhost:3000) tries to access a backend service (e.g., http://localhost:8080), the browser sends a preflight OPTIONS request to ensure that the request is allowed. If Spring Security isn't configured to handle these preflight requests correctly, it can block them and result in HTTP 401 Unauthorized errors.
To resolve this, you need to configure Spring Security to explicitly permit CORS preflight requests. This involves setting up CORS configurations in Spring Security to handle OPTIONS requests properly and ensure that cross-origin requests are allowed.
Create a new Spring Boot project using IntelliJ IDEA with the following options:
my-spring-cors-projectClick on the Next button.
Add the following dependencies to the Spring Boot project:
Click on the Create button.
After successfully creating the project, the folder structure will look like the below image:
In src/main/resources/application.properties, add the following properties:
spring.application.name=my-spring-cors-project
server.port=8080SecurityConfig ClassCreate the SecurityConfig class to configure Spring Security to handle CORS preflight requests.
SecurityConfig.java
Explaination:
securityFilterChain: Configures Spring Security to enable CORS and disable CSRF protection. The /api/test endpoint is allowed without authentication, while all other requests require authentication.corsFilter: Defines CORS settings, allowing all methods, headers, and credentials from http://localhost:3000.TestController ClassCreate the TestController class with a simple REST endpoint to test CORS handling.
TestController.java
Provides a simple GET endpoint /api/test that returns a confirmation message indicating that CORS is configured correctly.
The main class is the entry point of the Spring Boot application and does not require changes.
MySpringCorsProjectApplication.java:
Run the application on port 8080. Ensure it starts without errors.
Open the postman tool to send the GET request to the backend endpoint to check if CORS preflight handling is configured correctly.
Choose the following options:
Click on the Send button.
Result: We should see the response HTTP 200 OK indicating that the CORS preflight request has been allowed and shows the response message "CORS is configured correctly!" from the backend.
This example project demonstrates the how to implement and test the CORS preflight handling using Spring Boot and Spring Security. By correctly configuring the CORS in securityConfig.java and using the simple test endpoints, we can ensure that the cross-origin requests are managed securing, avoiding the common issues like HTTP 401 errors.