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

问题描述

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

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

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

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

谁能给我们一些指导,说明我们应该使用该库,还是手动编码我们的解决方案,或者使用某种第三方 JWT 库?

谢谢阅读!

标签: c#.netgoogle-signingoogle-api-dotnet-client

解决方案


我想这就是你要找的。

检索用户身份

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 视为稳定/完成。他们只有在发现关键问题时才会对其进行更改。


推荐阅读