Validating Google ID tokens in C#

后端 未结 3 1840
猫巷女王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: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.

提交回复
热议问题