给定的客户端 ID (GSI) 不允许给定的来源

The given origin is not allowed for the given client ID (GSI)

我正在重构我的“使用 Google 登录”,方法是在 http://localhost:8080 上用 gsi 替换 gapi

gapi 如何能毫无问题地工作,而 gsi 声称 The given origin is not allowed for the given client ID

gapi

<script src="https://apis.google.com/js/api:client.js" async defer></script>
window.gapi.load('auth2', () => {
  const auth2 = window.gapi.auth2.init({ client_id })
  auth2.signIn().then(console.log)
})

gsi

<script src="https://accounts.google.com/gsi/client" async defer></script>
<div id="g_id_onload"
     :data-client_id="client_id"
     data-login_uri="http://localhost:8080"
     data-auto_prompt="false">
</div>
<div class="g_id_signin"
     data-type="standard"
     data-size="large"
     data-theme="outline"
     data-text="sign_in_with"
     data-shape="rectangular"
     data-logo_alignment="left">
</div>

错误:The given origin is not allowed for the given client ID

我添加了没有端口的源来解决这个问题。

Key Point: Add both http://localhost and http://localhost:<port_number> to the Authorized JavaScript origins box for local tests or development.

来源:https://developers.google.com/identity/gsi/web/guides/get-google-api-clientid

在测试时找到了解决方案,因为尽管将站点域添加到 Authorised JavaScript origins,但我遇到了与此相关的以下错误消息:

Failed to load resource: the server responded with a status of 403 ()

[GSI_LOGGER]: The given origin is not allowed for the given client ID.

如果您使用的域名不是 localhost,请确保您通过 https 访问您的站点(如果证书尚不可用,请使用自签名证书/ 如果在您的非产品环境中进行测试)。

如果您的服务器将 Referrer-Policy 设置为 no-referrer,也会发生这种情况。 Google 需要此 HTTP header 否则对 https://accounts.google.com/gsi/button and https://accounts.google.com/gsi/iframe/select 的请求将以 400 响应并产生错误

如果使用头盔 - 以下配置将解决请求

referrerPolicy: {
  policy: 'strict-origin-when-cross-origin'
}

MDN article for Referrer-Policy

只需将以下元添加到 html 页面,您就可以开始了。

<meta name="referrer" content="strict-origin-when-cross-origin">