Validate Google ID Token in a .Net backend server

Viewed 1433

So, I have a Java-script and a .NET backend. In the Javascript i fetch the Google ID token when the user log in and the I would like to pass this to the backend and: 1) Validate the token 2) Extract the email, username etc.

This is explained in documentation for java: https://developers.google.com/identity/sign-in/web/backend-auth

The main thing is:

GoogleIdToken idToken = verifier.verify(idTokenString);

And:

String email = payload.getEmail();

So simple in Java! But what to do in .NET? I cannot find the documentation! I found the following thread, but it seems like a quite complicated solution. Is that really the most easy way?

Cheers, Mattias

2 Answers

I used Chris' lead and came up with the following, which works. You have to set the Audience (your app's client_id) yourself. The ValidateAsync(...) call will not throw an error if you don't supply this, but will assume you don't care about it, and it will succeed if everything else is good. Google asserts that such is insufficient and explains why in the link in the question.

Code:

public async Task<ActionResult> TokenLogin()
{
    var idToken = Request["idToken"];
    var settings = new GoogleJsonWebSignature.ValidationSettings() { Audience = new List<string>() { CLIENT_ID }  };

    string subject = null;
    try
    {
        var validPayload = await GoogleJsonWebSignature.ValidateAsync(idToken, settings);
        subject = validPayload.Subject;
    }
    catch (InvalidJwtException e)
    {
        Response.StatusCode = 403;
        Response.StatusDescription = "Your token was invalid.";
        // Should probably log this.
        return null;
    }

    // Obviously return something useful, not null.
    return null;
}
Related