CORS 允许来源限制不会导致服务器拒绝请求 [英] CORS allowed-origin restrictions aren’t causing the server to reject requests

查看:31
本文介绍了CORS 允许来源限制不会导致服务器拒绝请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Spring Boot v1.5.1,似乎我对 CORS 来源的限制不起作用.

I am using Spring Boot v1.5.1, and it seems my restriction on CORS origin is not working.

我的 application.properties 文件有以下一行 (ref1 ref2).

My application.properties file has the following line (ref1 ref2).

endpoints.cors.allowed-origins=http://mydomain.io

我的 REST 控制器如下所示.

My REST controller looks like the following.

@RestController
@CrossOrigin
@RequestMapping("/api/car")
public class CarCtrl {
  @Autowired
  private CarService carService;

  @GetMapping
  public Car get() {
    return carService.getLatest();
  }
}

但是,当我打开浏览器并输入 http://localhost:8080/api/car 时,我仍然可以访问 REST 端点.

However, when I open up a browser and type in http://localhost:8080/api/car I am still able to access the REST endpoint.

我也尝试如下更改我的注释,但这不起作用.

I also tried to change my annotation as follows, but that does not work.

@CrossOrigin("${endpoints.cors.allowed-origins}")

对我做错了什么有任何想法吗?

Any ideas on what I'm doing wrong?

请注意,我没有像这样使用 WebMvcConfigurerAdapter post.我真的需要扩展这个类来显式控制起源吗?我认为除了属性文件设置之外,@CrossOrigin 注释将能够控制允许的来源(而不是必须以编程方式进行).

Note that I am not using WebMvcConfigurerAdapter like this post. Do I really need to extends this class to explicitly control origin? I figured that the @CrossOrigin annotation in addition to the properties file setting would be able to control the allowed origins (as opposed to having to do so programmatically).

推荐答案

但是,当我打开浏览器并输入 http://localhost:8080/api/car 时,我仍然能够访问 REST 端点.

However, when I open up a browser and type in http://localhost:8080/api/car I am still able to access the REST endpoint.

CORS allowed-origins 设置不会导致服务器阻止请求.

CORS allowed-origins settings don’t cause servers to block requests.

而且由于服务器不会阻止请求,因此不会阻止您直接在浏览器中打开 URL.

And because the server isn’t blocking the request, that doesn’t prevent you from opening the URL directly in a browser.

同源策略是强加跨域限制的策略,同源策略仅适用于在 Web 浏览器中运行的 Web 应用程序中的前端 JavaScript,并且使用 XHR 或 Fetch 或 jQuery $.ajax(...) 或其他任何发出跨域请求的内容.

The same-origin policy is what imposes cross-origin restrictions, and the same-origin policy is only applied to frontend JavaScript in web applications running in a web browser, and using XHR or Fetch or jQuery $.ajax(…) or whatever to make cross-origin requests.

因此 CORS 不是导致服务器阻止请求的方法.因此,它也不是阻止用户直接导航到 URL 的方法,也不是阻止任何非网络应用程序工具(如 curl 或 Postman 或其他任何工具)的方法访问 URL.

So CORS isn’t a way to cause servers to block requests. And so it also isn’t a way to prevent users from being able to directly navigate to a URL, and isn’t a way to prevent any non-web-application tools like curl or Postman or whatever from accessing the URL.

这篇关于CORS 允许来源限制不会导致服务器拒绝请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆