Last active
May 13, 2023 01:15
-
-
Save Kambaa/062b9256bff190e59ebfcd113789df49 to your computer and use it in GitHub Desktop.
global cors definition spring boot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://stackoverflow.com/a/66590699/1020512 | |
https://reflectoring.io/spring-cors/ | |
https://www.tutorialspoint.com/spring_boot/spring_boot_cors_support.htm | |
https://www.baeldung.com/spring-cors | |
https://stackoverflow.com/questions/36968963/how-to-configure-cors-in-a-spring-boot-spring-security-application | |
https://spring.io/guides/gs/rest-service-cors/#global-cors-configuration | |
@Bean | |
public WebMvcConfigurer corsConfigurer() { | |
return new WebMvcConfigurer() { | |
@Override | |
public void addCorsMappings(CorsRegistry registry) { | |
registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:8080"); | |
} | |
}; | |
} | |
Configuring CORS globally: | |
You can also configure CORS globally for your entire application by creating a WebMvcConfigurer bean and overriding the addCorsMappings() method. Here's an example: | |
java | |
@Configuration | |
public class WebMvcConfig implements WebMvcConfigurer { | |
@Override | |
public void addCorsMappings(CorsRegistry registry) { | |
registry.addMapping("/api/**") | |
.allowedOrigins("http://localhost:4200") | |
.allowedMethods("GET", "POST", "PUT", "DELETE") | |
.allowedHeaders("*"); | |
} | |
} | |
In this example, the addCorsMappings() method is overridden to configure CORS for all paths | |
that start with /api. The allowedOrigins() method is used to specify the allowed domains, | |
allowedMethods() is used to specify the allowed HTTP methods, and allowedHeaders() is used | |
to specify the allowed request headers. | |
Note that CORS is a security feature that restricts cross-origin requests to prevent attacks | |
like cross-site scripting (XSS). Be careful when configuring CORS and make sure to only allow | |
trusted domains to access your APIs. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment