所以我有一个用AngularJS编写的客户端应用程序,用于创建一个移动应用程序(与Apache Cordova).将从移动设备加载html文件和JavaScript文件.
当我模拟它,我发送请求到REST API服务器我第一次得到
所请求的资源上不存在“Access-Control-Allow-Origin”头,因此原址’http:// localhost:82’不允许访问.
所以我添加了标题(“Access-Control-Allow-Origin:*”);在我的PHP REST API服务器.由于请求将来自移动设备,因此我无法指定特定的域.
现在,当凭证标志为真时,我得到“通配符”*’不能用于“访问控制允许原始”标头.
我终于找到了一个解决方案,但我不知道这样做是安全的.
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"); }
请告知这种工作方式.如果不安全或没有好处,请告诉我如何解决这个问题?
非常感谢!
就安全而言,请注意这个post about CORS的@Jules的评论:
Note that sending the HTTP Origin value back as the allowed origin
will allow anyone
to send requests to you with cookies,thus potentially stealing a session from a user
who logged into your site then viewed an attacker’s page. You either want to send ‘*’
(which will disallow cookies thus preventing session stealing) or the specific domains
for which you want the site to work.
另见以下例子:
Wildcard not accepted in Access-Control-Allow-Headers
Specify headers Access-Control-Allow-Headers
替代方法
您可以将origin标题设置为:
Access-Control-Allow-Origin: *
如果您不需要在您的请求中包含Cookie remove:
Access-Control-Allow-Credentials: true
从Access-Control-Allow-Headers中删除通配符并添加授权,然后将该标头作为您的授权请求的一部分,而不是将凭据传递给cookie,例如:
Authorization: Basic a2lkMT==