스프링 보안 CORS 필터
추가했습니다.Spring Security
기존 프로젝트에 적용할 수 있습니다.
부터 401을 수 있습니다.No 'Access-Control-Allow-Origin' header is present on the requested resource
이치노
는 '아니다'가 없기 입니다.Access-Control-Allow-Origin
헤더가 응답에 부가됩니다.이것을 수정하기 위해서, 델의 필터가 추가되어 있습니다.Filter
로그아웃 필터 앞에 체인을 두지만 필터는 요청에 적용되지 않습니다.
델의 오류:
는 XMLHttpRequest를 로드할 수 .
http://localhost:8080/getKunden
액세스 제어 허가 발신지 ★★★http://localhost:3000
따라서 접근이 허용되지 않습니다.[HTTP 401] 。
보안 구성:
@EnableWebSecurity
@Configuration
@ComponentScan("com.company.praktikant")
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private MyFilter filter;
@Override
public void configure(HttpSecurity http) throws Exception {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
source.registerCorsConfiguration("/**", config);
http.addFilterBefore(new MyFilter(), LogoutFilter.class).authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/*").permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
}
}
우리의 필터
@Component
public class MyFilter extends OncePerRequestFilter {
@Override
public void destroy() {
}
private String getAllowedDomainsRegex() {
return "individual / customized Regex";
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
final String origin = "http://localhost:3000";
response.addHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers",
"content-type, x-gwt-module-base, x-gwt-permutation, clientid, longpush");
filterChain.doFilter(request, response);
}
}
델의 어플리케이션
@SpringBootApplication
public class Application {
public static void main(String[] args) {
final ApplicationContext ctx = SpringApplication.run(Application.class, args);
final AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
annotationConfigApplicationContext.register(CORSConfig.class);
annotationConfigApplicationContext.refresh();
}
}
필터는 스프링 부트부터 등록됩니다.
2016-11-04 09:19:51.494 INFO 9704 --- [ost - start Stop - 1 ]o.s.b.w.servlet.FilterRegistrationBean : 필터: 'myFilter'를 [/*]에 매핑합니다.
생성된 필터 체인:
2016-11-04 09:19:52.729 INFO 9704 --- [ost - start Stop - 1 ]os . s . web .Default Security Filter Chain : 필터 체인 org.springframework를 만들고 있습니다.보안.web.disc.matcher 를 참조해 주세요.AnyRequestMatcher@1, [또는 스프링프레임워크]보안.web.disc.request.disc.를 참조합니다.WebAsyncManagerIntegrationFilter@5d8c5a8a, org.springframework.보안.web.web.discloss.를 참조해 주세요.SecurityContextPersistenceFilter@7d6938f, org.springframework.보안.web.web.discloss.를 참조해 주세요.HeaderWriterFilter@72aa89c, org.springframework.보안.web.web.deb.f.CsrfFilter@4af4df11, com.company.praktikant.MyFilter@5ba65db2, org.springframework.보안.web.authentication.logout 입니다.LogoutFilter@2330834f, org.springframework.보안.web.syslog request.RequestCacheAwareFilter@396532d1, org.springframework.보안.web.servletapi.SecurityContextHolderAwareRequestFilter@4fc0f1a2, org.springframework.보안.web.authentication 입니다.익명AuthenticationFilter@2357120f, org.springframework.보안.web.web.discloss.를 참조해 주세요.SessionManagementFilter@10867bfb, org.springframework.보안.web.access를 클릭합니다.ExceptionTranslationFilter@4b8bf1fb, org.springframework.보안.web.access를 클릭합니다.가로채다필터 보안인터셉터 @42063cf1]
응답:응답 헤더
우리도 봄부터 해결책을 시도했지만 효과가 없었어!컨트롤러의 @CrossOrigin 주석도 도움이 되지 않았습니다.
편집 1:
@Piotr Sowtysiak의 솔루션을 시험했다.생성된 필터 체인에 코르스 필터가 표시되어 있지 않지만, 같은 에러가 발생합니다.
2016-11-04 10:22:49.881 INFO 8820 --- [ost - start Stop - 1 ]os . s . web .Default Security Filter Chain : 필터 체인 org.springframework를 만들고 있습니다.보안.web.disc.matcher 를 참조해 주세요.AnyRequestMatcher@1, [또는 스프링프레임워크]보안.web.disc.request.disc.를 참조합니다.WebAsyncManagerIntegrationFilter@4c191377, org.springframework.보안.web.web.discloss.를 참조해 주세요.SecurityContextPersistenceFilter@28bad32a, org.springframework.보안.web.web.discloss.를 참조해 주세요.HeaderWriterFilter@3c3ec668, org.springframework.보안.web.web.deb.f.CsrfFilter@288460dd, org.springframework.보안.web.authentication.logout 입니다.LogoutFilter@1c9cd096, org.springframework.보안.web.authentication 입니다.Username PasswordAuthenticationFilter@3990c331, org.springframework.보안.web.authentication.ui 를 지정합니다.Default Login Page Generating Filter @1e8d4ac1, org.springframework.보안.web.authentication.www.BasicAuthenticationFilter@2d61d2a4, org.springframework.보안.web.syslog request.RequestCacheAwareFilter@380d9a9b, org.springframework.보안.web.servletapi.SecurityContextHolderAwareRequestFilter@abf2de3, org.springframework.보안.web.authentication 입니다.익명AuthenticationFilter@2a5c161b, org.springframework.보안.web.web.discloss.를 참조해 주세요.SessionManagementFilter@3c1fd3e5, org.springframework.보안.web.access를 클릭합니다.ExceptionTranslationFilter@3d7055ef, org.springframework.보안.web.access를 클릭합니다.가로채다필터 보안가로채기 @5d27725a]
그런데 스프링 보안 버전 4.1.3을 사용하고 있습니다.
Spring Security 4.1 이후로는 Spring Security가 CORS를 지원하도록 하는 적절한 방법입니다(Spring Boot 1.4/1.5에도 필요).
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
}
}
또, 다음과 같이 합니다.
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// http.csrf().disable();
http.cors();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(ImmutableList.of("*"));
configuration.setAllowedMethods(ImmutableList.of("HEAD",
"GET", "POST", "PUT", "DELETE", "PATCH"));
// setAllowCredentials(true) is important, otherwise:
// The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
configuration.setAllowCredentials(true);
// setAllowedHeaders is important! Without it, OPTIONS preflight request
// will fail with 403 Invalid CORS request
configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
문제를 해결하려면 , 다음의 어느쪽도 실시하지 말아 주세요.
http.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll();
web.ignoring().antMatchers(HttpMethod.OPTIONS);
참고 자료: http://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/cors.html
네, 이틀이 넘는 검색 끝에 문제를 해결했습니다.필터와 설정을 모두 삭제하고 대신 이 5줄의 코드를 어플리케이션클래스에 사용했습니다.
@SpringBootApplication
public class Application {
public static void main(String[] args) {
final ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:3000");
}
};
}
}
다른 솔루션에서 문제가 발생했기 때문에(특히 모든 브라우저에서 작동시키기 위해 엣지에서 "*"를 "Access-Control-Allow-Methods"의 유효한 값으로 인식하지 않음) 커스텀필터 컴포넌트를 사용해야 했습니다.이 컴포넌트는 결국 나에게 효과가 있었고, 내가 원하는 대로 실행했습니다.
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods",
"ACL, CANCELUPLOAD, CHECKIN, CHECKOUT, COPY, DELETE, GET, HEAD, LOCK, MKCALENDAR, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, REPORT, SEARCH, UNCHECKOUT, UNLOCK, UPDATE, VERSION-CONTROL");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Key, Authorization");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
public void init(FilterConfig filterConfig) {
// not needed
}
public void destroy() {
//not needed
}
}
스프링 부트2의 스프링 보안을 통해 CORS를 글로벌하게 설정할 수 있습니다(예를 들어 모든 개발 요구를 유효하게 합니다).다음 작업을 수행할 수 있는 작업은 다음과 같습니다.
@Bean
protected CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors()
.and().authorizeRequests()
.anyRequest().permitAll()
.and().csrf().disable();
}
내 인생의 8시간이란 시간은 절대 돌아오지 않을 거야
CorsConfiguration에서 Exposed Header와 Allowed Header를 모두 설정했는지 확인합니다.
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
configuration.setAllowedMethods(Arrays.asList("GET","POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
configuration.setExposedHeaders(Arrays.asList("Authorization", "content-type"));
configuration.setAllowedHeaders(Arrays.asList("Authorization", "content-type"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
필요 없는 것:
@Configuration @ComponentScan("com.company.praktikant")
@EnableWebSecurity
이미 가지고 있다@Configuration
그 안에, 왜 당신이 그걸 넣었는지 상상이 안 가요.@ComponentScan
거기.CORS 필터에 대해서는, 다음과 같이 하고 싶습니다.
@Bean public FilterRegistrationBean corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); bean.setOrder(0); return bean; }
Security Configuration 클래스로 이행하여 글로벌 메서드를 삭제하고 설정합니다.allowde orgins, 헤더 및 메서드를 두 번 설정할 필요가 없습니다.특히 필터와 스프링보안 설정에 다른 속성을 넣는 경우:)
위와 같이 "MyFilter" 클래스는 중복됩니다.
다음 항목도 제거할 수 있습니다.
final AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(); annotationConfigApplicationContext.register(CORSConfig.class); annotationConfigApplicationContext.refresh();
응용 프로그램클래스에서
마지막으로 작은 조언 - 질문과는 관련이 없습니다.URI에는 동사를 넣지 않는 것이 좋습니다.대신
http://localhost:8080/getKunden
HTTP GET 메서드를 사용하여http://localhost:8080/kunden
자원입니다.RESTful api 설계의 베스트 프랙티스에 대해서는, http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api 를 참조해 주세요.
5.0에서는 기본 메서드가 있으며 이 어댑터를 사용하지 않고도 직접 구현할 수 있으므로 클래스는 권장되지 않습니다.이 경우:
@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:3000");
}
}
참고 항목: Session cookie의 Same-Site 플래그
CORS 필터의 설명서에 의하면, 다음과 같습니다.
「스프링 MVC는, 컨트롤러의 주석을 사용해 CORS 설정을 세밀하게 서포트합니다.단, Spring Security와 함께 사용할 경우 내장된 CorsFilter를 사용하는 것이 좋습니다.이 CorsFilter는 Spring Security의 필터 체인보다 먼저 주문해야 합니다.
이런 게 있으면GET
에의 액세스/ajaxUri
:
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class AjaxCorsFilter extends CorsFilter {
public AjaxCorsFilter() {
super(configurationSource());
}
private static UrlBasedCorsConfigurationSource configurationSource() {
CorsConfiguration config = new CorsConfiguration();
// origins
config.addAllowedOrigin("*");
// when using ajax: withCredentials: true, we require exact origin match
config.setAllowCredentials(true);
// headers
config.addAllowedHeader("x-requested-with");
// methods
config.addAllowedMethod(HttpMethod.OPTIONS);
config.addAllowedMethod(HttpMethod.GET);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/startAsyncAuthorize", config);
source.registerCorsConfiguration("/ajaxUri", config);
return source;
}
}
물론 Spring Security 설정에서는 목록에 표시된 방법으로 URI에 액세스할 수 있어야 합니다.@Hendy Irawan 답변을 참조하십시오.
많은 곳에서 이 코드를 추가해야 하는 답이 나타납니다.
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
제 경우 예기치 않은 클래스 유형의 예외가 발생합니다. corsFilter()
이 필요하다CorsFilter
되어 모두 OK가 type 、 「 」 、 「 」 、 「 」 、 「 」 、 「 」 bean 의 「 」이것으로 모든 것이 정상입니다.
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
이 솔루션은 몇 시간 동안 조사한 후에 도움이 됩니다.
설정에서 core() 옵션을 초기화합니다.
@Override
public void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.etc
}
corsFilter에서 원하는 대로 credential, origin, Header 및 Method를 초기화합니다.
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new
UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
이 클래스는 사용할 필요가 없었습니다.
@Bean
public CorsConfigurationSource corsConfigurationSource() {
}
이 하고 이 클래스를 사용합니다.@EnableAutConfiguration
:
@Component
public class SimpleCORSFilter extends GenericFilterBean {
/**
* The Logger for this class.
*/
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
logger.info("> doFilter");
HttpServletResponse response = (HttpServletResponse) resp;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
//response.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(req, resp);
logger.info("< doFilter");
}
}
CORS를 글로벌하게 유효하게 하려면 , 부트에서 스프링 시큐러티를 사용하는 경우는, 다음의 2개의 장소를 변경할 필요가 있습니다.
1. 스프링 부트:
@Configuration
public class CorsConfiguration extends WebMvcConfigurationSupport {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowedMethods("*")
.allowCredentials(true);
}
}
할 수 있어요.WebMvcConfigurerAdapter
WebMvcConfigurer
.
2. 스프링 보안
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS).permitAll() //Permits your preflight request
}
이것에 의해, 모든 메서드, 모든 패스, 및 송신원이 유효하게 됩니다.따라서 주의하여 개발 시에만 사용하십시오.스프링 부트 2.3.3과 같이 동작합니다.풀어주다
Spring Boot 2 Spring Security에서는 아래 코드로 Cors 문제가 완벽하게 해결되었습니다.
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Collections.singletonList("*")); // <-- you may change "*"
configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(Arrays.asList(
"Accept", "Origin", "Content-Type", "Depth", "User-Agent", "If-Modified-Since,",
"Cache-Control", "Authorization", "X-Req", "X-File-Size", "X-Requested-With", "X-File-Name"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Bean
public FilterRegistrationBean<CorsFilter> corsFilterRegistrationBean() {
FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(corsConfigurationSource()));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
다음으로 Web Security Configuration에 대해 다음과 같이 추가했습니다.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.headers().frameOptions().disable()
.and()
.authorizeRequests()
.antMatchers("/oauth/tokeen").permitAll()
.antMatchers(HttpMethod.GET, "/").permitAll()
.antMatchers(HttpMethod.POST, "/").permitAll()
.antMatchers(HttpMethod.PUT, "/").permitAll()
.antMatchers(HttpMethod.DELETE, "/**").permitAll()
.antMatchers(HttpMethod.OPTIONS, "*").permitAll()
.anyRequest().authenticated()
.and().cors().configurationSource(corsConfigurationSource());
}
비슷한 문제가 있었습니다만, 다음과 같이 엔드 포인트의 데코레이터로부터 CORS 헤더를 설정할 필요가 있습니다.
@CrossOrigin(origins = "*", allowCredentials = "true")
@PostMapping(value = "/login")
또는
@CrossOrigin(origins = "*")
@GetMapping(value = "/verificationState")
따라서 요구를 대행 수신하는 것만으로 CORS 헤더를 수동으로 설정하고 200을 돌려보내는 것은 선택사항이 아닙니다.이는 경우에 따라서는 allowCredentials가 true여야 하고 와일드카드가 허용되지 않기 때문입니다.물론 CORS 레지스트리가 도움이 되었겠지만, 당사의 고객은 Android와 iOS에서 캐패시터를 사용하고 있기 때문에 등록할 도메인이 따로 없습니다.따라서 제 생각에 가장 깔끔한 방법은 엔드 포인트에 직접 프리플라이트를 파이프로 연결하여 그들이 처리하도록 하는 것입니다.이렇게 해결했습니다.
@Component
public class PreflightFilter extends OncePerRequestFilter {
private static final Logger logger = LoggerFactory.getLogger(PreflightFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
if (CorsUtils.isPreFlightRequest(request)) {
logger.info("Preflight request accepted");
SecurityContextHolder.getContext().setAuthentication(createPreflightToken(request));
}
chain.doFilter(request, response);
}
private UsernamePasswordAuthenticationToken createPreflightToken(HttpServletRequest request) {
UserDetails userDetails = new User("Preflight", "",
true, true, true, true,
Stream.of(new SimpleGrantedAuthority("AppUser")).collect(Collectors.toSet()));
UsernamePasswordAuthenticationToken preflightToken =
new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
preflightToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
return preflightToken;
}
}
엔드포인트 데코레이터는 예상대로 와일드카드처럼 작동하지 않습니다.
이것에 의해, CORS 의 credential을 가지는 모든 송신원이 허가됩니다.
@Component
public class FilterChainConfig implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
if (servletResponse instanceof HttpServletResponse){
HttpServletResponse response = (HttpServletResponse)servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
String requestOrigin = request.getHeader("Origin");
response.setHeader("Access-Control-Allow-Origin", requestOrigin);
response.setHeader("Access-Control-Allow-Credentials", "true");
//response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS, HEAD");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "*");
filterChain.doFilter(request, response);
}
}
}
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
.....
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/api/**").authenticated().and().httpBasic().and().csrf().disable();
}
@Bean
protected CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
......
}
아래 샘플 사용
@Configuration
@EnableConfigurationProperties(BasicAuthConfigProperties.class)
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final BasicAuthConfigProperties basicAuth;
public SecurityConfiguration(BasicAuthConfigProperties basicAuth) {
this.basicAuth = basicAuth;
}
protected void configure(HttpSecurity http) throws Exception {
http.cors();
}
}
언급URL : https://stackoverflow.com/questions/40418441/spring-security-cors-filter
'programing' 카테고리의 다른 글
봄철 웹 소켓 인증 및 인가 (0) | 2023.03.10 |
---|---|
AngularJS: ng-read only (0) | 2023.03.10 |
부모 컨트롤러의 변수를 상속할 수 있습니까? (0) | 2023.03.10 |
페이지를 갱신하지 않고 URI를 변경하려면 어떻게 해야 합니까? (0) | 2023.03.10 |
워드프레스 테마에서 쇼트코드 사용 (0) | 2023.03.10 |