Validate Google ID Token in a .Net backend server

。_饼干妹妹 提交于 2019-12-05 23:11:48

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).

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