스프링 부트에 여러 크로스 오리진 URL 추가
spring-boot 어플리케이션에서 cors header를 설정하는 예를 찾았습니다.우리는 기원이 많기 때문에 나는 그것들을 추가해야 한다.다음 사항이 유효합니까?
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://domain1.com")
.allowedOrigins("http://domain2.com")
.allowedOrigins("http://domain3.com")
}
}
3개의 도메인이 사용하지 않는 한 테스트할 방법이 없습니다.다만, 「domain3.com」만 설정되어 있는 것이 아니고, 3개의 기원을 설정하고 있는 것을 확인합니다.
EDIT:의 이상적인 사용 예는 (application.properties에서) 도메인 목록을 삽입하고 그것을 allowed Origins로 설정하는 것입니다.가능합니까
예
@Value("${domainsList: not configured}")
private List<String> domains;
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins(domains)
}
}
스프링 부트에는 응답에 헤더를 추가하는 @CrossOrigin 주석이 있습니다.
1. For multiple:
@CrossOrigin(origins = {"http://localhost:7777", "http://someserver:8080"})
@RequestMapping(value = "/abc", method = RequestMethod.GET)
@ResponseBody
public Object doSomething(){
...
}
2. If you wanna allow for everyone then simply use.
@CrossOrigin
설정 방법에 따라 세 번째 원점만 설정되고 나머지 두 개는 사라집니다.
세 개의 원점을 모두 설정하려면 쉼표로 구분된 문자열로 전달해야 합니다.
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://domain1.com","http://domain2.com"
"http://domain3.com");
}
실제 코드는 다음 URL에서 찾을 수 있습니다.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableWebMvc
@PropertySource("classpath:config.properties")
public class CorsClass extends WebMvcConfigurerAdapter {
@Autowired
private Environment environment;
@Override
public void addCorsMappings(CorsRegistry registry) {
String origins = environment.getProperty("origins");
registry.addMapping("/api/**")
.allowedOrigins(origins.split(","));
}
}
이것은 동작하지 않습니다.대신 시도해 주세요.
registry.addMapping("/api/**")
.allowedOrigins(
"http://domain1.com",
"http://domain2.com",
"http://domain3.com")
Springboot에서 글로벌 CORS를 사용하고 여러 도메인을 추가하려면 다음과 같이 하십시오.
속성 파일에서 다음과 같이 속성 및 도메인을 추가할 수 있습니다.
allowed.origins=*.someurl.com,*.otherurl.com,*.someotherurl.com
또한 구성 클래스:
@EnableWebMvc
@Configuration
public class AppConfig extends WebMvcConfigurerAdapter {
private static final Logger logger = LoggerFactory.getLogger(AppConfig.class);
@Value("#{'${allowed.origins}'.split(',')}")
private List<String> rawOrigins;
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
logger.info("Adding CORS to the service");
registry.addMapping("/**")
.allowedOrigins(getOrigin())
.allowedMethods(HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.OPTIONS.name())
.allowedHeaders(HttpHeaders.AUTHORIZATION, HttpHeaders.CONTENT_TYPE, "accessToken", "CorrelationId", "source")
.exposedHeaders(HttpHeaders.AUTHORIZATION, HttpHeaders.CONTENT_TYPE, "accessToken", "CorrelationId", "source")
.maxAge(4800);
}
/**
* This is to add Swagger to work when CORS is enabled
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
};
}
public String[] getOrigin() {
int size = rawOrigins.size();
String[] originArray = new String[size];
return rawOrigins.toArray(originArray);
}
}
봄철 대응의 CORS를 찾고 있는 여러분과 다른 분들에게 도움이 될 것입니다.
커스텀 주석을 만들고 API에 주석을 붙입니다.
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@CrossOrigin
public @interface CrossOriginsList {
public String[] crossOrigins() default {
"http://domain1.com", "http://domain1.com"
"http://domain1.com", "http://domain1.com"
// Pass as many as you want
};
}
이 커스텀 주석을 사용하여 API에 주석을 달 수 있습니다.
@CrossOriginsList
public String methodName() throws Exception
{
//Business Logic
}
나한텐 완벽하게 잘 작동했어!!!
리소스/어플리케이션.syslogl
server: port: 8080 servlet: contextPath: /your-service jetty: acceptors: 1 maxHttpPostSize: 0 cors: origins: - http://localhost:3001 - https://app.mydomainnnn.com - https://app.yourrrrdooomain.com
config/Config.java
package com.service.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties("server")
public class Config {
private int port;
private Cors cors;
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
public Cors getCors() {
return this.cors;
}
public void setCors(Cors cors) {
this.cors = cors;
}
public static class Cors {
private List<String> origins = new ArrayList<>();
public List<String> getOrigins() {
return this.origins;
}
public void setOrigins(List<String> origins) {
this.origins = origins;
}
}
}
config/WebConfig.java
package com.service.config;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.service.controller")
@PropertySource("classpath:application.yaml")
public class WebConfig extends WebMvcConfigurerAdapter {
@Autowired
private Environment environment;
@Autowired
private Config config;
@Override
public void addCorsMappings(CorsRegistry registry) {
System.out.println("configuring cors");
String[] origins = config.getCors().getOrigins().toArray(String[]::new);
System.out.println(" - origins " + Arrays.toString(origins));
registry.addMapping("/**")
.allowedOrigins(origins);
}
}
이것은 Springboot 2.7.0을 사용하는 경우에 유효합니다.
application.yml
allowedOrigins: http://localhost:[*], http://*.your-domain.com:[*]
CorsConfig
@Configuration
public class CorsConfig {
@Value("${allowedOrigins}")
private List<String> domains;
@Bean
public FilterRegistrationBean<CorsFilter> corsFilterRegistrationBean(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
// very important to allow patterns !!!
config.setAllowedOriginPatterns(domains);
source.registerCorsConfiguration("/**", config);
.....
return new FilterRegistrationBean<>(new CorsFilter(source));
}
언급URL : https://stackoverflow.com/questions/39623211/add-multiple-cross-origin-urls-in-spring-boot
'programing' 카테고리의 다른 글
| 메모리 DB를 사용한 스프링 부트 테스트 (0) | 2023.03.26 |
|---|---|
| JSON 피드에 값이 존재하는지 확인하는 더 나은 방법 (0) | 2023.03.26 |
| 각도 부트스트랩 날짜 선택기 날짜 형식이 ng-model 값 형식을 지정하지 않음 (0) | 2023.03.26 |
| 응답 라우터: 정의되지 않은 속성 'pathname'을 읽을 수 없습니다. (0) | 2023.03.26 |
| "Expected to return a value at end of arrow function" 경고를 수정하려면 어떻게 해야 합니까? (0) | 2023.03.26 |