Validating Google ID tokens in C#

后端 未结 3 1825
猫巷女王i
猫巷女王i 2021-02-13 22:38

I need to validate a Google ID token passed from a mobile device at my ASP.NET web api.

Google have some sample code here but it relies on a JWT NuGet package which is .

相关标签:
3条回答
  • 2021-02-13 23:05

    ClientId also needs to be passed, which should be set from Google API Console. If only pass TokenId, GoogleJsonWebSignature throws error. This answer is in addition to @edmundpie answer

    var settings = new GoogleJsonWebSignature.ValidationSettings()
    {
     Audience = new List<string>() { "[Placeholder for Client Id].apps.googleusercontent.com" }
    };
    
    var validPayload = await GoogleJsonWebSignature.ValidateAsync(model.ExternalTokenId, settings);
    
    0 讨论(0)
  • 2021-02-13 23:13

    The challenge is validating the JWT certificate in the ID token. There is currently not a library I'm aware of that can do this that doesn't require .Net 4.5 and until there is a solution for JWT validation in .NET 4.0, there will not be an easy solution.

    However, if you have an access token, you can look into performing validation using oauth2.tokeninfo. To perform basic validation using token info, you can do something like the following:

    // Use Tokeninfo to validate the user and the client.
    var tokeninfo_request = new Oauth2Service().Tokeninfo();
    tokeninfo_request.Access_token = _authState.AccessToken;
    var tokeninfo = tokeninfo_request.Fetch();
    if (userid == tokeninfo.User_id
        && tokeninfo.Issued_to == CLIENT_ID)
    {
        // Basic validation succeeded
    }
    else
    {
        // The credentials did not match.
    }
    

    The information returned from the Google OAuth2 API tells you more information about a particular token such as the client id it was issued too as well as its expiration time.

    Note You should not be passing around the access token but instead should be doing this check after exchanging a one-time code to retrieve an access token.

    0 讨论(0)
  • 2021-02-13 23:24

    According to this github issue, you can now use GoogleJsonWebSignature.ValidateAsync method to validate a Google-signed JWT. Simply pass the idToken string to the method.

    var validPayload = await GoogleJsonWebSignature.ValidateAsync(idToken);
    Assert.NotNull(validPayload);
    

    If it is not a valid one, it will return null.

    Note that to use this method, you need to install Google.Apis.Auth nuget firsthand.

    0 讨论(0)
提交回复
热议问题