0

I'd like to know how I can get the user details, First name, Last name and Email Id, using the access token from Google API. Currently, I'm using the following piece of code which returns me

{ "error": "invalid_grant", "error_description": "Bad Request" },

The server side c# code using RestSharp

var client = new RestClient("https://oauth2.googleapis.com/token");
var request = new RestRequest(Method.POST);
request.AddParameter("code", accessToken);
request.AddParameter("redirect_uri", "[my domain ]/oauth?provider=google");
request.AddParameter("client_id", "[ClientId]");
request.AddParameter("client_secret", "[ClientSecret]");
request.AddParameter("scope", "openid email profile");
request.AddParameter("grant_type", "authorization_code");

IRestResponse response = client.Execute(request);

In the OAuth consent screen in Google Console, I haven't added anything under Scopes. Could this be a problem? I'm accessing only basic information. Also, I'm not sure which scopes to add.

Thanks in advance and appreciate any help on this.

Update: I tried adding this scope - https://www.googleapis.com/auth/userinfo.profile but its still same issue.

This is the flow I have. I have this link on the page

https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=<Redirect url>?provider=google&prompt=consent&response_type=code&client_id=<Client id>&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+openid&access_type=offline

On clicking this link, the user is redirected to the Google authentication page. Once authenticated it redirects to the redirect URL with the access token which is then validated on the server-side and gets the user info.

Frenz
  • 687
  • 1
  • 10
  • 22
  • You should get the first name and last name when you request the profile data. see this answer https://stackoverflow.com/questions/7130648/get-user-info-via-google-api – johnny 5 Nov 06 '20 at 14:45
  • Thanks @johnny5. I've tried that. It doesn't work. That is mainly if you are doing it client side so Google checks the cookies. I'm trying to do it at server side. – Frenz Nov 06 '20 at 15:32
  • Anything you do client side you can do server side. Login with the OAuth Flow, and parse the profile data in your accounts controller, in the ExternalLoginCallback – johnny 5 Nov 06 '20 at 15:46
  • I don't see the code which handles the AuthorizationCode, are you sure you're completing the oauth login, I don't see where you use the AuthorizationCode to request an OAuth Token – johnny 5 Nov 06 '20 at 15:48
  • Thanks @johnny5 for getting back on this. I've updated the post with more details. Hope this helps. – Frenz Nov 09 '20 at 22:46

0 Answers0