简体   繁体   中英

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 that "An error occurred while sending the request." but 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"
}

"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."
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM