我什么时候应该真正设置“ Access-Control-Allow-Credentials”?为“真实”在我的响应标题中? [英] When should I really set "Access-Control-Allow-Credentials" to "true" in my response headers?

查看:482
本文介绍了我什么时候应该真正设置“ Access-Control-Allow-Credentials”?为“真实”在我的响应标题中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MDN 说,当必须在站点 Access-Control-Allow-Crendentials 站点之间交换Cookie,授权标头或TLS客户端证书之类的凭据时,必须将其设置为 true

MDN says, when the credentials like cookies, authorisation header or TLS client certificates has to be exchanged between sites Access-Control-Allow-Crendentials has to be set to true.

考虑两个站点A- https://example1.xyz.com ,另一个是B- https://example2.xyz.com 。现在,我必须从A向B发出http Get 请求。当我从AI请求B时,

Consider two sites A - https://example1.xyz.com and another one is B- https://example2.xyz.com. Now I have to make a http Get request from A to B. When I request B from A I am getting,


所请求的
资源上没有'Access-Control-Allow-Origin'标头。来源'访问noreferrer> http://example1.xyz.com

因此,我在B中添加以下响应标头

So, I'm adding the following response headers in B

response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));

这解决了相同的原点错误,我可以向B提出请求。何时以及为什么我应该set

This resolves the same origin error and I'm able to request to B. When and why should I set

response.setHeader("Access-Control-Allow-Credentials", "true");

当我用Google搜索解决此问题时,同源 >错误,大多数建议同时使用两个标头。我不清楚要使用第二个 Access-Control-Allow-Credentials

When I googled to resolve this same-origin error, most of them recommended using both headers. I'm not clear about using the second one Access-Control-Allow-Credentials.


  1. 何时应同时使用两者?

  2. 为什么要设置 Access -Control-Allow-Origin origin 从请求标头而不是通配符 * 获得?

  1. When should I use both?
  2. Why should I set Access-Control-Allow-Origin to origin obtained from request header rather than wildcard *?

请引用一个示例以更好地理解它。

Please quote me an example to understand it better.

推荐答案

如果您希望请求也能够发送cookie,则需要允许凭据。如果您需要授权传入的请求,则基于会话ID cookie是常见的原因。

Allow-Credentials would be needed if you want the request to also be able to send cookies. If you needed to authorize the incoming request, based off a session ID cookie would be a common reason.

设置通配符可使任何站点向您的端点发出请求。如果请求与您定义的白名单相匹配,则设置允许原产地很常见。某些浏览器将缓存允许响应,并且如果您还从另一个域请求了相同的内容,则可能导致请求被拒绝。

Setting a wildcard allows any site to make requests to your endpoint. Setting allow to origin is common if the request matches a whitelist you've defined. Some browsers will cache the allow response, and if you requested the same content from another domain as well, this could cause the request to be denied.

这篇关于我什么时候应该真正设置“ Access-Control-Allow-Credentials”?为“真实”在我的响应标题中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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