Можете ли вы полностью отключить поддержку CORS в Spring?
Как описано в CORS, предварительный запрос не выполняется из-за стандартного заголовка, если вы отправляете запросы конечным точкам OPTIONS
с установленными заголовками Origin
и Access-Control-Request-Method
тогда они перехватываются средой Spring, и ваш метод не выполняется. @CrossOrigin
решением является использование аннотаций @CrossOrigin
чтобы Spring не возвращал 403
. Тем не менее, я генерирую свой код API с помощью Swagger Codegen, и поэтому я просто хочу отключить это и реализовать свои ответы OPTIONS
вручную.
Так вы можете отключить перехват CORS в Spring?
Ответы
Ответ 1
Из их документации:
Если вы используете Spring Web MVC
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
}
}
Если вы используете Spring Boot:
@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
}
};
}
}
Юрий Юников ответ тоже правильный. Но мне не нравится "пользовательский" фильтр.
Если у вас есть Spring Web Security, который вызывает у вас проблемы. Проверьте этот SO Ответ.
Ответ 2
Попробуйте добавить следующий фильтр (вы можете настроить его для собственных нужд и поддерживаемых методов):
@Component
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
final FilterChain filterChain) throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH, HEAD");
response.addHeader("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
response.addHeader("Access-Control-Expose-Headers", "Access-Control-Allow-Origin, Access-Control-Allow-Credentials");
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addIntHeader("Access-Control-Max-Age", 10);
filterChain.doFilter(request, response);
}
}
Ответ 3
Для более новых версий весенней загрузки:
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("*");
}
}
Ответ 4
Я использую Spring Security в своем приложении Spring Boot и разрешаю доступ из определенных доменов (или из всех доменов).
Мой WebSecurityConfig:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
// ...
@Override
protected void configure(HttpSecurity http) throws Exception {
// add http.cors()
http.cors().and().csrf().disable().authorizeRequests()
.antMatchers("/get/**").permitAll()
.antMatchers("/update/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.httpBasic(); // Authenticate users with HTTP basic authentication
// REST is stateless
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
// To enable CORS
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(ImmutableList.of("https://www.yourdomain.com")); // www - obligatory
// configuration.setAllowedOrigins(ImmutableList.of("*")); //set access from all domains
configuration.setAllowedMethods(ImmutableList.of("GET", "POST", "PUT", "DELETE"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
Иногда необходимо очистить историю браузера перед тестированием.
Подробную информацию можно увидеть здесь:
http://appsdeveloperblog.com/crossorigin-restful-web-service/
Просто для тех, кто использует Angular. Из Angular я запускаю запросы к бэкенду:
export class HttpService {
username = '..';
password = '..';
host = environment.api;
uriUpdateTank = '/update/tank';
headers: HttpHeaders = new HttpHeaders({
'Content-Type': 'application/json',
Authorization: 'Basic ' + btoa(this.username + ':' + this.password)
});
constructor(private http: HttpClient) {
}
onInsertTank(tank: Tank) {
return this.http.put(this.host + this.uriUpdateTank, tank, {
headers: this.headers
})
.pipe(
catchError(this.handleError)
);
}
...
}
Старая версия.
В моем приложении Spring Boot другие способы не сработали:
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, x-auth-token");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials", "true");
if (!(request.getMethod().equalsIgnoreCase("OPTIONS"))) {
try {
chain.doFilter(req, res);
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
System.out.println("Pre-flight");
response.setHeader("Access-Control-Allowed-Methods", "POST, GET, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "authorization, content-type,x-auth-token, " +
"access-control-request-headers, access-control-request-method, accept, origin, authorization, x-requested-with");
response.setStatus(HttpServletResponse.SC_OK);
}
}
public void init(FilterConfig filterConfig) {
}
public void destroy() {
}
}