Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authenticate Google access token with ASP.NET Core backend server

I have Angular2 on client and ASP.NET Core on server side. I use JavaScriptServices (aspnetcore-spa template).
For authentication I use OpenIddict and I follow example here.

Now I am on the server side in Controller class method and I would like to validate id_token because this is suggested on this side:

Important: Do not use the Google IDs returned by getId() or the user's profile information to communicate the currently signed in user to your backend server. Instead, send ID tokens, which can be securely validated on the server.

And I would also like to register user (save email, profile ...) in my database through ASP.NET Core identity.

I would like to use Google API client Library for .NET to get user information and store refresh_token. Years ago I manage to do it with PHP, but I can't figure it out with .NET.
I download nuget packages: Google.Apis, Google.Apis.OAuth2.v2, Google.Apis.Plus.v1.

I am not sure which nuget package I need for this, which class should I use, how to set Google ServerKey and how to get user information from information which I get from gapi.signin2 button.

In simple:
How can I validate id_token from .NET with Google .NET Client library?

like image 655
Makla Avatar asked Feb 16 '17 10:02

Makla


1 Answers

I found solution here. It is old, but it works.

var googleInitializer = new BaseClientService.Initializer();
googleInitializer.ApiKey = this.config["Authentication:Google:ServerKey"];
Oauth2Service ser = new Oauth2Service(googleInitializer);
Oauth2Service.TokeninfoRequest req = ser.Tokeninfo();
req.AccessToken = request.AccessToken;  //access token received from Google SignIn button
Tokeninfo userinfo = await req.ExecuteAsync();

I didn't figure it out how to get Display name and picture on server. But it can be done on client:

onGoogleLoginSuccess(user: gapi.auth2.GoogleUser)
{
    console.log("basic profile", user.getBasicProfile());
}

If someone knows more updated solution or how to retrieve basic user profile on server, please share it.

In addition I can use Google+, but careful because Google Account is not Google+ Account. I didn't have + account and get error:

Google.Apis.Requests.RequestError Not Found [404] Errors [ Message[Not Found] Location[ - ] Reason[notFound] Domain[global] ]

in code:

var plusService = new PlusService(googleInitializer);
Person me = await plusService.People.Get(userinfo.UserId).ExecuteAsync();

but it is possible to get all user information (picture, display name, first name, last name, birthday ...)

like image 141
Makla Avatar answered Sep 28 '22 05:09

Makla