OWIN Google 身份验证 - 如何获得 id_token?

OWIN Google authentication - how to get id_token?

我已进行设置,以便能够使用 Google 成功进行身份验证。代码看起来像这样:

app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions
{
    AuthenticationType = "Google",
    Caption = "Sign-in with Google",
    SignInAsAuthenticationType = signInAsType,
    ClientId = "yyy",
    ClientSecret = "zzz",
    Provider = new GoogleOAuth2AuthenticationProvider
    {
        OnAuthenticated = async context =>
        {
            // How can I access id_token here?
        }
    }
});

当调用 Authenticated 方法时,我可以通过 GoogleOAuth2AuthenticatedContext 访问有关用户的各种信息。但是,我需要能够从 Google 中读取原始的 id_token,以便我可以将其添加到声明中并稍后在身份验证流程中访问它。有什么办法可以做到吗?

首先,请确保您使用的是 3.0.1 位,因为最初的 3.0.0 版本不包含此方案所需的 TokenResponse 属性。

然后,更新您的 OnAuthenticated 通知以从令牌响应中提取身份令牌:

var token = context.TokenResponse.Value<string>("id_token");

要解析 "OpenID identifier",您可以使用 JWT 安全令牌处理程序从身份令牌中提取声明:

var jwt = new JwtSecurityToken(token);
var identifier = jwt.Claims.FirstOrDefault(claim => string.Equals(claim.Type, "openid_id", StringComparison.InvariantCulture));