You need to enable JavaScript to run this app. ASP.NET迁移至新版Sign In With Google时onSignIn函数获取用户资料问题
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET迁移至新版Sign In With Google时onSignIn函数获取用户资料问题

新版Sign In With Google用户信息获取方案

新版Google登录废弃了旧版googleUser.getBasicProfile()接口,所有用户基础信息都封装在回调返回的JWT格式id_token的payload字段中,你可以根据场景选择前端直接解析或后端验签后获取信息。

前端直接解析方案(仅适合测试/非敏感场景)

首先你需要确保在初始化Google登录时已经正确绑定了回调函数,回调逻辑示例如下:

// 新版登录回调函数,需要在按钮配置的data-callback属性或初始化参数中指定该函数名
function handleCredentialResponse(response) {
  // 调用新版API自带的解码方法解析JWT凭证
  const userInfo = google.accounts.id.decodeCredential(response.credential);

  // 与旧版接口的字段对应关系
  console.log('ID: ' + userInfo.sub); // 等价于旧版 profile.getId(),用户唯一标识
  console.log('Name: ' + userInfo.name); // 等价于旧版 profile.getName()
  console.log('Image URL: ' + userInfo.picture); // 等价于旧版 profile.getImageUrl()
  console.log('Email: ' + userInfo.email); // 等价于旧版 profile.getEmail(),需开通email scope权限

  // 需要传给ASP.NET后端时,请直接传递完整的response.credential(即id_token),不要传递前端解析的用户信息
}

后端验签获取信息方案(生产环境推荐)

为了避免请求伪造,生产环境必须将前端传回的id_token发送到ASP.NET后端做验签后再提取用户信息,实现步骤如下:

  1. 先安装所需NuGet包:
    System.IdentityModel.Tokens.Jwt、Microsoft.IdentityModel.Protocols.OpenIdConnect

  2. 后端验证及信息提取代码示例:

using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

public class GoogleAuthService
{
    // 替换为你自己的Google OAuth客户端ID
    private const string ClientId = "YOUR_GOOGLE_CLIENT_ID";
    private static readonly IConfigurationManager<OpenIdConnectConfiguration> _configManager = 
        new ConfigurationManager<OpenIdConnectConfiguration>(
            "https://accounts.google.com/.well-known/openid-configuration",
            new OpenIdConnectConfigurationRetriever());

    public async Task<Dictionary<string, string>> GetValidatedUserInfoAsync(string idToken)
    {
        var openIdConfig = await _configManager.GetConfigurationAsync(CancellationToken.None);
        var validationParams = new TokenValidationParameters
        {
            ValidIssuer = "https://accounts.google.com",
            ValidAudience = ClientId,
            IssuerSigningKeys = openIdConfig.SigningKeys,
            ValidateLifetime = true
        };

        var tokenHandler = new JwtSecurityTokenHandler();
        try
        {
            SecurityToken validatedToken;
            tokenHandler.ValidateToken(idToken, validationParams, out validatedToken);
            var jwtToken = (JwtSecurityToken)validatedToken;

            return new Dictionary<string, string>
            {
                ["user_id"] = jwtToken.Claims.First(c => c.Type == "sub").Value,
                ["name"] = jwtToken.Claims.First(c => c.Type == "name").Value,
                ["avatar"] = jwtToken.Claims.First(c => c.Type == "picture").Value,
                ["email"] = jwtToken.Claims.First(c => c.Type == "email").Value
            };
        }
        catch (SecurityTokenException)
        {
            // Token无效,返回空或抛出业务异常
            return null;
        }
    }
}

注意事项

  • 若返回的email字段为空,需在初始化Google登录配置中添加scope: "email"参数申请邮箱权限
  • 旧版返回的ID和新版的sub字段完全等价,可以直接映射到原有业务逻辑的用户唯一标识
  • 生产环境绝对不能直接信任前端解析传回的用户信息,必须走后端验签流程

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 18:06:01