Validate Google ID Token in a .Net backend server

雨燕双飞 提交于 2019-12-01 06:40:55

问题


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


回答1:


You probably want GoogleJsonWebSignature.ValidateAsync(...).

This provides almost the same behaviour as the Java you posted. The only missing functionality is to check the audience field of the token (This omission is tracked issue #1042).




回答2:


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;
}


来源:https://stackoverflow.com/questions/45090396/validate-google-id-token-in-a-net-backend-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!