You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

迁移至Google Identity Service后如何获取用户邮箱及Profile信息

迁移Google身份认证JS库后获取用户Profile(邮箱)问题解决

问题背景

正在将原有对接Google Cloud Platform的JS认证代码迁移至新的Google Identity Services(GIS)库,目前遇到无法获取用户Profile(以获取邮箱)的问题,旧方法已弃用。

旧弃用代码

旧方法通过auth2对象获取用户Profile:

var profile = auth2.currentUser.get().getBasicProfile();
var email = profile.getEmail();

新代码现状

已通过新的token模式获取到access_token,代码片段如下:

{
    client_id: vm.clientId,
    scope: SCOPE,
    callback: (tokenResponse) => {
        if (tokenResponse && tokenResponse.access_token) {
            access_token = tokenResponse.access_token;

            // 此处如何获取Profile?
        }
    }
}

尝试过的无效方法

曾尝试调用gapi.client.oauth2.userinfo.get()但未成功:

gapi.client.oauth2.userinfo.get().execute(function (resp) {
   console.log(resp);
})

正确解决方案

迁移指南提到应直接使用JWT格式的CredentialResponse对象中的凭证字段处理用户Profile数据,以下是两种可行方案:

方案1:解析id_token获取Profile信息

如果你的认证请求包含openid email权限(需在scope中添加),tokenResponse里会包含id_token字段,这是一个JWT令牌,可直接解析出用户邮箱等Profile信息:

callback: (tokenResponse) => {
    if (tokenResponse && tokenResponse.id_token) {
        // 手动解码JWT payload部分,也可使用jwt-decode等库简化操作
        const payload = JSON.parse(atob(tokenResponse.id_token.split('.')[1]));
        const email = payload.email;
        const userName = payload.name;
        // 还可从payload中获取头像地址(picture)、用户唯一标识(sub)等字段
    }
}

注意:必须确保scope参数包含openid email,否则不会返回id_token。

方案2:用access_token调用用户信息API

之前调用无效大概率是因为未正确初始化gapi.client或权限不足,正确操作步骤如下:

  1. 确保scope包含https://www.googleapis.com/auth/userinfo.email权限
  2. 先加载并初始化gapi.client后再调用接口:
// 先加载gapi客户端
gapi.load('client', () => {
    gapi.client.init({
        discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/oauth2/v2/rest"]
    }).then(() => {
        // 设置已获取到的access_token
        gapi.client.setToken({access_token: access_token});
        // 调用用户信息API
        gapi.client.oauth2.userinfo.get().then((resp) => {
            console.log("用户邮箱:", resp.result.email);
        }).catch((err) => {
            console.error("获取用户信息失败:", err);
        });
    });
});

关于CredentialResponse对象说明

在新的GIS库中,使用google.accounts.oauth2.initTokenClient初始化客户端时,回调函数的tokenResponse就是CredentialResponse对象,它包含access_token、id_token(请求openid权限时返回)、expires_in等核心字段,直接从该对象提取对应内容即可。


内容的提问来源于stack exchange,提问作者Chadz001

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 23:15:34