尽管使用了过滤器,但仍被 CORS 策略阻止
Posted
技术标签:
【中文标题】尽管使用了过滤器,但仍被 CORS 策略阻止【英文标题】:Getting blocked by CORS policy despite using a Filter 【发布时间】:2019-12-20 22:32:56 【问题描述】:我有这个SimpleCORSFilter
:
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCORSFilter implements Filter
@Override
public void init(FilterConfig fc) throws ServletException
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException
HttpServletResponse response = (HttpServletResponse) resp;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "PATCH,POST,GET,OPTIONS,DELETE,PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN");
if ("OPTIONS".equalsIgnoreCase(request.getMethod()))
response.setStatus(HttpServletResponse.SC_OK);
else
chain.doFilter(req, resp);
@Override
public void destroy()
除了我创建自己的ResponseEntity
对象以返回分页内容的这一端点外,一切正常:
@RequestMapping(value = ROOT + "/businessId/reviews", method = RequestMethod.GET)
public @ResponseBody HttpEntity<PagedResources<MenuReviewDto>> getAll(
@PathVariable(name = "businessId") Long businessId,
@RequestParam(value = "page", defaultValue = "0") Integer page,
@RequestParam(value = "size", defaultValue = "10") Integer size,
Sort sort,
PagedResourcesAssembler assembler
)
Pageable pageable = PageRequest.of(page, size, sort);
Page<ReviewDto> reviews = this.reviewService.getAll(businessId, pageable);
PagedResources<ReviewDto> pagedResources = assembler.toResource(reviews);
return new ResponseEntity<>(pagedResources, HttpStatus.OK);
这是目前唯一一个失败的请求给我一个典型的错误:
Access to XMLHttpRequest at 'https://192.168.1.144:8443/r/api/v1/admin/businesses/3/reviews?page=0&sort=createdAt,desc&size=5' from origin 'https://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
奇怪的事情:
在此请求期间进行调试时,我可以看到我的 SimpleCORSFilter
中的 doFilter()
正在被调用。所以应该添加标题?!
【问题讨论】:
【参考方案1】:好的,这很快。我把这个贴在这里是因为它让我有点吃惊。
我在日志输出中发现了这个:
2019-08-1...ExceptionResolver : Resolved [org...Exception: Could not write JSON: ..
yadda,yadda,yadda ..
.. java.util.ArrayList[0]->mahlzeit.shared.review.ReviewRatingDto["isCut"])]
现在,让我们看看isCut
是什么:
public class ReviewRatingDto
private Boolean isCut;
// ..
public void setIsCut(boolean isCut)
this.isCut = isCut;
public boolean getIsCut()
return isCut;
问题:它是返回 boolean
而不是 Boolean
的 getter。这当然是使用我选择的 IDE 懒惰地自动生成的代码,最终是我自己的错误,但请注意,由此产生的错误可能会导致您质疑您的 CORS 设置..
【讨论】:
以上是关于尽管使用了过滤器,但仍被 CORS 策略阻止的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Spring Security 过滤器中授权 CORS