Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate Google id token with C#

Tags:

c#

google-api

I'm currently creating a web application on which the user can login via his Google account. This works client side but I would also like to secure REST API calls. To do so, I send the "Google id token" with each request via the "Authorization" header. Now, I would like to verify in C# that the token passed is valid. I found that there is a .NET library to do so but I didn't find anywhere any clear documentation on how to simply validate the token.

Does anyone have some pointer for this?

like image 504
ssougnez Avatar asked May 23 '17 17:05

ssougnez


People also ask

How do I verify my Google ID token?

To do so securely, after a successful sign-in, send the user's ID token to your server using HTTPS. Then, on the server, verify the integrity and authenticity of the ID token and retrieve the uid from it. You can use the uid transmitted in this way to securely identify the currently signed-in user on your server.

How do I refresh Google ID token?

You can refresh an Identity Platform ID token by issuing an HTTP POST request to the securetoken.googleapis.com endpoint. The refresh token's grant type, always "refresh_token".


2 Answers

My answer is the same as the answer above with a little bit more details.

using Google.Apis.Auth;
using Google.Apis.Auth.OAuth2;

GoogleJsonWebSignature.Payload payload = await GoogleJsonWebSignature.ValidateAsync(Token);
...

The payload object contains all the information that you need.

like image 189
Wen W Avatar answered Sep 25 '22 16:09

Wen W


For future reference the following verifications are checked internally by the Google.Apis.Auth library and no extra validations are required (both passing settings or checking the payload):

  • bad jwt (null, empty, too long, missing signature)
  • wrong algorithm
  • invalid signature
  • invalid issuer
  • signature time without tolerance

The following however require input by the developer in order to be validated. They can be passed with GoogleJsonWebSignature.ValidationSettings:

  • audience
  • hosted domain
  • signature time with tolerance

Source: Google.Apis.Auth.Tests/GoogleJsonWebSignatureTests.cs

According to the docs, the token must be validated by verifying the signature with Google's public key. Also check the aus, iss and exp claims, and the hd claim if applies. Therefore only the aus (and hd) have to be tested explicitly by the developer.

try
{
   //...
   var validationSettings = new GoogleJsonWebSignature.ValidationSettings
   {
      Audience = new string[] { "[google-signin-client_id].apps.googleusercontent.com" }
   };

   var payload = await GoogleJsonWebSignature.ValidateAsync(idToken, validationSettings);
   //...
}
catch (InvalidJwtException ex)
{
   //...
}
like image 21
Veglos Avatar answered Sep 25 '22 16:09

Veglos