问题描述
我知道已经有很多关于CORS的问题,但是它们似乎并没有回答我的问题.
I know there are a lot of questions concerning CORS already but they don't seem to answer my question.
因此,我有一个用Angular编写的客户端应用程序,它将用于创建移动应用程序(使用Apache Cordova). html文件和JavaScript文件将从移动设备加载.当我进行模拟并将请求发送到REST API服务器时,我首先得到了所请求的资源上没有'Access-Control-Allow-Origin'标头.因此,不允许对源'http://localhost:82
'的访问".所以我添加了header("Access-Control-Allow-Origin:*");在我的php REST API服务器中.我无法指定特定的域,因为请求将来自移动设备.
So I have a client app written in Angular which will be used to create a mobile app (with Apache Cordova). The html files and JavaScript files will be loaded from the mobile device.When I simulate that and I send requests to the REST API server I first got"No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:82
' is therefore not allowed access".So I added header("Access-Control-Allow-Origin: *"); in my php REST API Server. I cannot specify a specific domain as the requests will come from the mobile devices.
现在,我获得了当凭据标记为true时,'Access-Control-Allow-Origin'标头中不能使用通配符'*'."
Now I got to "A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true."
我终于找到了解决方案,但不确定将其保持这种状态是安全的.
I finally found a solution but I'm not sure it is safe to keep it like this.
在我的php REST API服务器中,我添加了以下内容:
In my php REST API Server I added this:
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
header("Access-Control-Allow-Headers: *, X-Requested-With, Content-Type");
header("Access-Control-Allow-Methods: GET, POST, DELETE, PUT");
}
请就这种工作方式提出建议.如果它不安全或根本没有好处,您能告诉我如何解决此问题吗?
Please advise on this way of working. If it is not secure or no good at all, can you please tell me how to solve this issue?
非常感谢!
推荐答案
响应仅在Access-Control-Allow-Headers中具有接受的标头,请勿使用通配符.
Response should only have the accepted headers in Access-Control-Allow-Headers, don't use wildcard.
为了安全起见,请在此有关CORS的帖子中注意@Jules的评论:
As far as it being safe, note the comment from @Jules in this post about CORS:
另请参见以下示例:
Access-Control-Allow-Header中不接受通配符
指定标头Access-Control-Allow-Headers
替代方法
您可以将原始标头设置为:
You can just set the origin header to:
Access-Control-Allow-Origin: *
如果您不需要在请求中包含Cookie,请删除:
If you don't need to include cookies in your request remove:
Access-Control-Allow-Credentials: true
从Access-Control-Allow-Headers中删除通配符,然后添加Authorization,然后将该标头作为您的授权请求的一部分传递,而不是在cookie中传递凭据,例如:
Remove the wildcard from Access-Control-Allow-Headers and add Authorization and then pass that header as part of your request for authorization, instead of passing credentials in a cookie, ex:
Authorization: Basic a2lkMT==
此外,将OPTIONS添加到允许的方法中.
Also, add the OPTIONS to allowed methods.
这篇关于角度:当凭据标记为true时,不能在'Access-Control-Allow-Origin'标头中使用通配符'*'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!