使用 Google 登录 - 我们如何在 .net 中验证 Google ID 令牌服务器端?缺少代码示例,库似乎已弃用

Sign in with Google - how can we verify the Google ID token server side in .net? Code sample missing, library appears deprecated

我们正在根据最新文档将“使用 Google 登录”实现到 MVC5 应用程序中,这与我们在 web 上看到的大多数示例完全不同且更直接。

该过程的一部分是“验证服务器端的 Google ID 令牌”,如本页所述:https://developers.google.com/identity/gsi/web/guides/verify-google-id-token

我们在这里被告知“与其编写自己的代码来执行这些验证步骤,我们强烈建议使用适合您平台的 Google API 客户端库”,这很公平, 但是

a) 该页面上没有 .net 的代码示例, b) 项目文档似乎与使用 Google 登录没有任何关系 c) 如果您真的在这里查看 .net 客户端库的 github:https://github.com/googleapis/google-api-dotnet-client 它说“此客户端库受支持,但仅处于维护模式”,这让我想知道我们是否是这个意思正在使用它。

任何人都可以就我们是应该使用该库、手动编写解决方案还是使用某种第三方 JWT 库提供一些指导?

感谢阅读!

希望这篇Url对您有所帮助: https://googleapis.dev/dotnet/Google.Apis.Auth/latest/api/Google.Apis.Auth.GoogleJsonWebSignature.html

using Google.Apis.Auth;
using Google.Apis.Auth.OAuth2;

GoogleJsonWebSignature.Payload payload = await GoogleJsonWebSignature.ValidateAsync(Token);

这是一个关于如何验证您的令牌的小例子。

我想这就是您要找的。

Retrieving the user identity

using Google.Apis.Auth;
using System;
using System.Threading;
using System.Threading.Tasks;

public class IAPTokenVerification
{
    /// <summary>
    /// Verifies a signed jwt token and returns its payload.
    /// </summary>
    /// <param name="signedJwt">The token to verify.</param>
    /// <param name="expectedAudience">The audience that the token should be meant for.
    /// Validation will fail if that's not the case.</param>
    /// <param name="cancellationToken">The cancellation token to propagate cancellation requests.</param>
    /// <returns>A task that when completed will have as its result the payload of the verified token.</returns>
    /// <exception cref="InvalidJwtException">If verification failed. The message of the exception will contain
    /// information as to why the token failed.</exception>
    public async Task<JsonWebSignature.Payload> VerifyTokenAsync(
        string signedJwt, string expectedAudience, CancellationToken cancellationToken = default)
    {
        SignedTokenVerificationOptions options = new SignedTokenVerificationOptions
        {
            // Use clock tolerance to account for possible clock differences
            // between the issuer and the verifier.
            IssuedAtClockTolerance = TimeSpan.FromMinutes(1),
            ExpiryClockTolerance = TimeSpan.FromMinutes(1),
            TrustedAudiences = { expectedAudience }
        };

        return await JsonWebSignature.VerifySignedTokenAsync(signedJwt, options, cancellationToken: cancellationToken);
    }
}

库处于维护模式,因为它已被 Google 视为稳定/完成。他们只会在发现关键时才对其进行更改 问题。