C#C
C#2y ago
v0fbu1vm

Verify Google Id Token: FormatException

I'm using google sign in on my client. Before authenticating the user I want to Verify the ID Token which I get from the client. On the server side. I'm trying to validate the ID Token (jwt) by using Google.Apis.Auth nuget package. But I'm getting a format exception. Here is the code:
/// <summary>
///   Handler for verifying Google ID tokens.
/// </summary>
public class VerifyGoogleIdTokenHandler(IConfiguration configuration)
    : IRequestHandler<VerifyGoogleIdTokenCommand, Result<GoogleJsonWebSignature.Payload>>
{
    private readonly GoogleJsonWebSignature.ValidationSettings _settings = new()
    {
        Audience = new[]
        {
            configuration[ConfigurationKeys.GoogleWebClientId], configuration[ConfigurationKeys.GoogleAndroidClientId]
        }
    };

    public async Task<Result<GoogleJsonWebSignature.Payload>> Handle(VerifyGoogleIdTokenCommand request,
        CancellationToken cancellationToken)
    {
        try
        {
            var payload = await GoogleJsonWebSignature.ValidateAsync(request.IdToken, _settings);
            if (payload == null)
                throw new InvalidJwtException("Invalid ID token");

            return Result<GoogleJsonWebSignature.Payload>.Success(payload);
        }
        catch (Exception ex)
        {
            return Result<GoogleJsonWebSignature.Payload>.Failure("Invalid ID token", new[] { ex.ToString() }, 400);
        }
    }
}
Was this page helpful?