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 令牌:
-
验证跨站请求伪造 (CSRF) 令牌 https://developers.google.com/identity/gsi/web/guides/verify-google-id-token and
- 验证 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)