From b9e06d2f7043e5061f1109905265aecca9e340c6 Mon Sep 17 00:00:00 2001 From: "IIPL\\14261" Date: Mon, 9 Dec 2024 17:39:15 +0530 Subject: [PATCH] Add Dynamic CORS Configuration for Spring Boot Application --- .../com/app/config/CorsConfiguration.java | 29 +++++++++++++++++++ src/main/resources/application-local.yml | 4 +++ 2 files changed, 33 insertions(+) create mode 100644 src/main/java/com/app/config/CorsConfiguration.java diff --git a/src/main/java/com/app/config/CorsConfiguration.java b/src/main/java/com/app/config/CorsConfiguration.java new file mode 100644 index 0000000..a1382e9 --- /dev/null +++ b/src/main/java/com/app/config/CorsConfiguration.java @@ -0,0 +1,29 @@ +package com.app.config; + +import lombok.NonNull; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +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 CorsConfiguration { + @Value("#{'${spring.web.allow.cors}'.split(',')}") + private String[] allowedEndPoint; + + @Bean + public WebMvcConfigurer setCorsWebMvcConfigurer() { + return new WebMvcConfigurer() { + @Override + public void addCorsMappings(@NonNull CorsRegistry registry) { + registry.addMapping("/**") + .allowedOrigins(allowedEndPoint) + .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS") + .allowedHeaders("*") + .allowCredentials(true) + .maxAge(3600); + } + }; + } +} diff --git a/src/main/resources/application-local.yml b/src/main/resources/application-local.yml index d2f8b2d..d640f6f 100644 --- a/src/main/resources/application-local.yml +++ b/src/main/resources/application-local.yml @@ -2,3 +2,7 @@ app: logs: path: C:/${spring.application.name}/logs +spring: + web: + allow: + cors: http://localhost:8080,http://localhost:4200 \ No newline at end of file