How to Configure Cors in Spring Boot
Configure CORS in a Spring Boot REST application to make it accessible from a frontend application such as React or Angular. 1. What i...
Configure CORS in a Spring Boot REST application to make it accessible from a frontend application such as React or Angular.
1. What is CORS and why do we need CORS?
CORS or Cross-Origin Resource Sharing is a browser security feature that restricts accessing the resource of server b from an HTTP request initiated by a script coming from server a.
Normally, we have our API server running on the backend such as api.czetsuyatech.com. This is where actual data fetching and manipulation happens.
On the other side, we have our frontend client which is normally powered by either React, Angular, or Vue. For example, czetsuya.com. And this client fetches data from our API server.
1.1 How CORS work?
- Perform a CORS preflight request.
- If CORS headers from the server match the client, proceed. Otherwise, throw a CORS error.
- Return response with data.
2. Different Ways of Configuring CORS
2.1 CrossOrigin Annotation
2.2 Globally via Spring WebMvcConfigurer
package com.czetsuyatech.core.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedMethods("*") .allowedHeaders("*") .allowedOrigins("http://192.168.1.9:3000") .allowCredentials(false) .maxAge(-1); } }
- "*" means it will accept any allowable value for that field. For example, allowedMethods will accept GET, POST, PUT, DELETE, OPTIONS, etc. @see org.springframework.http.HttpMethod.
- allowedOrigins, tells Spring to only accept Ajax requests from these URL patterns.
- maxAge - indicates how long to cache the result of a CORS preflight request.
3. Deployment and Testing
To see how CORS work, clone the following GIT repositories:
- https://github.com/czetsuya/spring-cors - Spring Boot project
- https://github.com/czetsuya/spring-cors-nextjs - React/NextJS project
3.1 Requirements
- OpenJDK 11 - https://developers.redhat.com/products/openjdk/download
- Node - https://nodejs.org/en/download
- Yarn - in a terminal execute, npm install --global yarn
Post a Comment