Created
October 29, 2019 14:38
-
-
Save cmphil/54f1cd3381b43d93ea24afa80c2db88c to your computer and use it in GitHub Desktop.
Example: Spring Boot CORS config
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
package com.foo.config; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import org.springframework.context.annotation.Configuration; | |
import org.springframework.core.env.Environment; | |
import org.springframework.web.servlet.config.annotation.CorsRegistration; | |
import org.springframework.web.servlet.config.annotation.CorsRegistry; | |
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; | |
import java.util.Arrays; | |
@Configuration | |
public class CORSConfig implements WebMvcConfigurer { | |
private final Environment env; | |
private static final Logger LOGGER = LoggerFactory.getLogger(CORSConfig.class); | |
public SecurityConfig(Environment env) { | |
this.env = env; | |
} | |
@Override | |
public void addCorsMappings(CorsRegistry registry) { | |
String mapping = env.getProperty("security.policy.cors.mapping"); | |
String[] urls = env.getProperty("security.policy.cors.allowed-origins", String[].class); | |
String[] methods = env.getProperty("security.policy.cors.allowed-methods", String[].class); | |
String[] headers = env.getProperty("security.policy.cors.allowed-headers", String[].class); | |
Long maxAge = env.getProperty("security.policy.cors.max-age", Long.class); | |
CorsRegistration reg = null; | |
if (mapping != null) { | |
reg = registry.addMapping(mapping); | |
LOGGER.info("Added Mapping: " + mapping); | |
if (urls != null) { | |
reg.allowedOrigins(urls); | |
LOGGER.info("Added Origins: " + Arrays.toString(urls)); | |
} | |
if (methods != null) { | |
reg.allowedMethods(methods); | |
LOGGER.info("Added Methods: " + Arrays.toString(methods)); | |
} | |
if (headers != null) { | |
reg.allowedHeaders(headers); | |
LOGGER.info("Added Headers: " + Arrays.toString(headers)); | |
} | |
if (maxAge != null) { | |
reg.maxAge(maxAge); | |
LOGGER.info("Added Max Age: " + maxAge); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment