[英]Spring Boot CORS blocks DELETE requests
Whenever I try to send request to delete endpoint with axios, I get the following error:每当我尝试使用 axios 发送删除端点的请求时,都会收到以下错误:
Access to XMLHttpRequest at 'http://localhost:8080/api/payment_card/delete/1234123412343433' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource从源“http://localhost:3000”访问“http://localhost:8080/api/payment_card/delete/1234123412343433”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头
Axios request is built as following : Axios 请求构建如下:
.delete(
"http://localhost:8080/api/payment_card/delete/" + selectedCardId ,
{
headers: {
Authorization: `Bearer ${token}`,
"Access-Control-Allow-Origin": "**"
},
}
)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});```
My java WebSecurityConfig stays as follow:
Override protected void configure(HttpSecurity http) throws Exception {
http = http.cors().and().csrf().disable();
http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
// Set session management to stateless
http = http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and();
// Set unauthorized requests exception handler
http = http
.exceptionHandling()
.authenticationEntryPoint(new AuthException())
.and();
http.addFilterBefore(requestFilter, UsernamePasswordAuthenticationFilter.class);
}
And in the controller, mapping is :在控制器中,映射是:
public ResponseEntity<PaymentCard> deletePaymentCard(@PathVariable Long cardNumber) {
PaymentCard pCard = paymentCardService.deletePaymentCard(cardNumber);
return new ResponseEntity<>(pCard, HttpStatus.OK);
}
I tried many solutions like adding @CrossOrigin annotation, making CorsFilter but nothing seems to help at all.我尝试了许多解决方案,例如添加 @CrossOrigin 注释,制作 CorsFilter 但似乎没有任何帮助。 Ultimately, I've changed DeleteMapping to GetMapping in my controller but I feel like http policy can catch me to custody at any time :( Thanks for your time and help in advance.
最终,我在控制器中将 DeleteMapping 更改为 GetMapping,但我觉得 http 策略可以随时抓住我的监护权 :( 感谢您的时间和提前帮助。
CorsConfiguration.applyPermitDefaultValues()
allows not all methods as one may assume, but following methods only: GET, HEAD, POST. CorsConfiguration.applyPermitDefaultValues()
并不像人们假设的那样允许所有方法,但仅允许以下方法:GET、HEAD、POST。
To allow DELETE method, you can use following code:要允许 DELETE 方法,您可以使用以下代码:
http.cors().configurationSource(c -> {
CorsConfiguration corsCfg = new CorsConfiguration();
// All origins, or specify the origins you need
corsCfg.addAllowedOriginPattern( "*" );
// If you really want to allow all methods
corsCfg.addAllowedMethod( CorsConfiguration.ALL );
// If you want to allow specific methods only
// corsCfg.addAllowedMethod( HttpMethod.GET );
// corsCfg.addAllowedMethod( HttpMethod.DELETE );
// ...
});
If we configure CorsConfiguration
explicitly, I recommend not to use applyPermitDefaultValues()
, but specify all desired methods explicitly.如果我们显式配置
CorsConfiguration
,我建议不要使用applyPermitDefaultValues()
,而是显式指定所有需要的方法。 Then nobody will need to remember what methods exactly are enabled by applyPermitDefaultValues()
, and such code will be easier to understand.然后没有人需要记住
applyPermitDefaultValues()
究竟启用了哪些方法,这样的代码将更容易理解。
I could have a class that implements Filter with the following methods我可以有一个使用以下方法实现过滤器的类
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
final 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", "Authorization, Content-Type");
response.setHeader("Access-Control-Max-Age", "3600");
if (HttpMethod.OPTIONS.name().equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig config) throws ServletException {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.