“使用 Google 登录”按钮的 data-login_uri 属性应使用什么?

2024-03-21

我正在尝试实现“使用 Google 登录”按钮,如此处记录的:https://developers.google.com/identity/gsi/web/guides/display-button https://developers.google.com/identity/gsi/web/guides/display-button

我对它的期望感到困惑data-login_uri如下图所示(取自上面链接的文档):

<div id="g_id_onload"
     data-client_id="YOUR_GOOGLE_CLIENT_ID"
     data-login_uri="https://your.domain/your_login_endpoint"
     data-auto_prompt="false">
</div>

我已正确配置应用程序的客户端 ID,并且可以完成 Google 弹出窗口提供的大部分登录/身份验证流程。但是,一旦弹出窗口关闭,它就会尝试POST到我指定的任何 URIdata-login_uri.

这让我相信我们需要一个后端端点来做......某物...但我无法找到有关此端点应如何表现的任何文档,因此我不确定与后端开发人员沟通的要求是什么。

我错过了什么?


TL;DR您的服务器上需要一个后端进程(用 PHP、Python、Node 等编写),可以中继 token_id(从div你引用的)到谷歌进行验证。

Why?

谷歌的文档说:

警告:请勿在后端服务器上接受纯用户 ID,例如通过 GoogleUser.getId() 方法获取的用户 ID。修改后的客户端应用程序可以将任意用户 ID 发送到您的服务器以模拟用户,因此您必须使用可验证的 ID 令牌来安全地获取服务器端登录用户的用户 ID。

Details

的价值data-auto_prompt参数应指向后端 API 或可执行 CGI 进程的端点。

假设您的域名是“example.com”。需要有一个端点,或者该端点上的可执行 cgi 脚本能够捕获 POST 请求,并且application/x-www-form-urlencoded编码。可能是这样的:https://www.example.com/login https://www.example.com/login.

在此端点,脚本/路由应该能够提取“tokenid”

Google 的文档描述了后端必须在两个地方执行的操作:

验证服务器端的 Google ID 令牌:

  1. 验证跨站请求伪造 (CSRF) 令牌 https://developers.google.com/identity/gsi/web/guides/verify-google-id-token and
  2. 验证 ID 令牌的完整性 https://developers.google.com/identity/sign-in/web/backend-auth#verify-the-integrity-of-the-id-token

下面是使用 Flask 框架的“登录”路由的 python 代码片段: (建议使用虚拟环境,并且需要 pip 安装两个 google api。)

在命令行: pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

# Required imports from google API
from google.oauth2 import id_token
from google.auth.transport import requests

@bp.route('/login', methods=['POST'])
def login():

    # Supplied by g_id_onload
    tokenid = request.form['credential']

    # Hardcoded client ID. Substitute yours.
    clientid = XXXXX

    # Display the encrypted credential
    current_app.logger.debug(f"Token = {tokenid}")
   
    try:
        idinfo = id_token.verify_oauth2_token(tokenid, 
                requests.Request(), clientid)

        # Display the verified user information
        current_app.logger.debug(f"idinfo = {idinfo}")
    
        # jsonify returns a response object
        user_data = jsonify({
                'username': idinfo['email'],
                'name': idinfo['name'],
                'id': idinfo['sub']
            })
        return  user_data

    except:
        return Response(status=404)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

“使用 Google 登录”按钮的 data-login_uri 属性应使用什么? 的相关文章

随机推荐