Reputation: 215
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
Upvotes: 3
Views: 2031
Reputation: 371
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;
}
Upvotes: 3
Reputation: 1705
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).
Upvotes: 4