Learn AspNet
Learn AspNet

Reputation: 1612

Post Request to https://oauth2.googleapis.com/token keeps failing in Code, Works on Postman

I am trying to get access token through a post request to https://oauth2.googleapis.com/token, but it keeps giving me an error:

"An error occurred while sending the request."

It works fine through Postman and Fiddler with same content. Can you please tell me what am I doing wrong in the code?

Uri myUri = new Uri(request.AbsoluteUrl);
string googleCode = HttpUtility.ParseQueryString(myUri.Query).Get("code");

var googleClientId = "435335443.apps.googleusercontent.com";
var uri = "https://oauth2.googleapis.com/token";
var googleClientSecret = "Test123";
var _httpClient = new HttpClient();
var data = new GoogleAccessToken
           {
              clientId = googleClientId,
              clientSecret = googleClientSecret,
              grant_type = "authorization_code",
              redirect_uri = "http://localhost:53419/GoogleOAuth", //Same as one I used to get the code
              code = googleCode
          };

var jsonRequest = JsonConvert.SerializeObject(data);
var rawResponse = await _httpClient.PostAsync(uri, new StringContent(jsonRequest, Encoding.UTF8, "application/json"));

Error - "An error occurred while sending the request."

Json request

{"code":"657856987608768-asfdsacsdcsd","client_Id":"435335443.apps.googleusercontent.com","client_secret":"Test123","redirect_uri":"http://localhost:53419/GoogleOAuth","grant_type":"authorization_code"}

My Postman Request works fine

POST /token HTTP/1.1
Host: oauth2.googleapis.com
Content-Type: application/json


{
"code":"657856987608768-asfdsacsdcsd",
"client_id":"435335443.apps.googleusercontent.com",
"client_secret":"Test123",
"redirect_uri":"http://localhost:53419/GoogleOAuth",
"grant_type":"authorization_code"
}

Upvotes: 2

Views: 10119

Answers (1)

Oleg Skidan
Oleg Skidan

Reputation: 617

"client_Id" 

from your request is not the same as

"client_id"

in Postman call. Try to change your request in Postman, so you can understand what is wrong with your code request.

You can catch something like this in your response:

{
   "error": "invalid_request",
   "error_description": "Could not determine client ID from request."
}

Upvotes: 1

Related Questions