How to fix “Bad request” error when sending Rest request to Google Oauth2 SSO in HttpClientHow do you set the Content-Type header for an HttpClient request?Oauth2: The remote server returned an error: (400) Bad RequestGoogle Play Android Developer API from C#/.NET service - (400) Bad Request400 BAD request HTTP error code meaning?PHP - Exchange authorization code for refresh and access tokens (No cURL)How can I get the authorization token from localhost (ie without redirect_url)?TOAuth2Authenticator: How do i refresh an expired token?Microsoft Access Token Request Error - 400 Bad RequestYouTube API Error, Node.jsOauth2 Authentication handle code programmatically

Parallel resistance in electric circuits

How can I discourage sharing internal API keys within a company?

Can druids change their starting cantrips each day?

Permutations in Disguise

Is "you will become a subject matter expert" code for "you'll be working on your own 100% of the time"?

Specific filter on the set using Python

How To Make Earth's Oceans as Brackish as Lyr's

Speedometer as a symbol into awesomebox

How does a linear operator act on a bra?

How are unbalanced coaxial cables used for broadcasting TV signals without any problems?

What is a realistic time needed to get a properly trained army?

How to conditionally add the "show-row-number-column" attribute to the lightning-datatable

Is a suit against a University Dorm for changing policies on a whim likely to succeed (USA)?

What are uses of the byte after BRK instruction on 6502?

How to control the output voltage of a solid state relay

What made 4/4 time the most common time signature?

How do I create indestructible terrain?

Has SHA256 been broken by Treadwell Stanton DuPont?

What organs or modifications would be needed for a life biological creature not to require sleep?

Are space camera sensors usually round, or square?

Is low emotional intelligence associated with right-wing and prejudiced attitudes?

2000s space film where an alien species has almost wiped out the human race in a war

Can I conceal an antihero's insanity - and should I?

Is there a tool to measure the "maturity" of a code in Git?



How to fix “Bad request” error when sending Rest request to Google Oauth2 SSO in HttpClient


How do you set the Content-Type header for an HttpClient request?Oauth2: The remote server returned an error: (400) Bad RequestGoogle Play Android Developer API from C#/.NET service - (400) Bad Request400 BAD request HTTP error code meaning?PHP - Exchange authorization code for refresh and access tokens (No cURL)How can I get the authorization token from localhost (ie without redirect_url)?TOAuth2Authenticator: How do i refresh an expired token?Microsoft Access Token Request Error - 400 Bad RequestYouTube API Error, Node.jsOauth2 Authentication handle code programmatically






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I´m trying to learn how to implement Googles Oauth2 SSO login function. So far I´ve gotten to the point where everything works except when I try to send a request to "https://accounts.google.com/o/oauth2/token" using REST in C# to get the Access_code/Token. I´ve registered my localhost and the corresponding port on google and I´ve managed to get my POST request to work in POSTMAN however when i try sending a request in C# my HttpRequestMessage returns 400 bad request.



First I have an Authorization.aspx page that runs a command that redirects the users to googles authorization page where the user login and then gets redirected to my page http://localhost:64716/GoogleCallBack.aspx which picks up the response. In the page it picks up the authorization code and tries to send a POST request to the base URL. I´ve tried running it in POSTMAN where it works (although only with a new authorization code). So I know it is my C# code that is the problem. I´ve tried using webrequest and I´ve also tried changing the Media type to application/Json and application/x-www-form-urlencoded



 protected void Page_Load(object sender, EventArgs e)


string Error = Request.QueryString["error"];

string Code = Request.QueryString["code"];
if (Error != null)
else if (Code != null)


string UserId = Request.QueryString["state"];
int Id = Convert.ToInt32(UserId);
string AccessToken = string.Empty;
string RefreshToken = ExchangeAuthorizationCode(Id, Code, out AccessToken);
string Url = "Authorize.aspx?UserId=" + UserId;
Response.Redirect(Url, true);


private string ExchangeAuthorizationCode(int userId, string code, out string accessToken)

string baseurl = "https://accounts.google.com/o/oauth2/token";
accessToken = string.Empty;
string ClientSecret = ConfigurationManager.AppSettings["ClientSecrete"];
string ClientId = ConfigurationManager.AppSettings["ClientId"];

string RedirectUrl = "http://localhost:64716/GoogleCallBack.aspx";

using (var client = new HttpClient())

client.BaseAddress = new Uri(baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/Json"));

var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("Code", code));
nvc.Add(new KeyValuePair<string, string>("Client_id", ClientId));
nvc.Add(new KeyValuePair<string, string>("Client_secret", ClientSecret));
nvc.Add(new KeyValuePair<string, string>("Redirect_uri", RedirectUrl));
nvc.Add(new KeyValuePair<string, string>("Grant_type", "authorization_code"));
nvc.Add(new KeyValuePair<string, string>("access_type", "offline"));

var req = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress) Content = new FormUrlEncodedContent(nvc) ;
var resres = client.SendAsync(req).Result;

return "temp";






I want my response to be statuscode 200 with an access_token from google (Like it does in Postman)










share|improve this question
























  • Ive not seen oauth tokens tried to be sent like this. Do your headers match the postman ones?

    – BugFinder
    Mar 28 at 10:58











  • In this particular example no, in Postman i use application/x-www-form-urlencoded instead of application/json but I have tried adding that too. It did not solve my problem.

    – Rawmouse
    Mar 28 at 12:03

















1















I´m trying to learn how to implement Googles Oauth2 SSO login function. So far I´ve gotten to the point where everything works except when I try to send a request to "https://accounts.google.com/o/oauth2/token" using REST in C# to get the Access_code/Token. I´ve registered my localhost and the corresponding port on google and I´ve managed to get my POST request to work in POSTMAN however when i try sending a request in C# my HttpRequestMessage returns 400 bad request.



First I have an Authorization.aspx page that runs a command that redirects the users to googles authorization page where the user login and then gets redirected to my page http://localhost:64716/GoogleCallBack.aspx which picks up the response. In the page it picks up the authorization code and tries to send a POST request to the base URL. I´ve tried running it in POSTMAN where it works (although only with a new authorization code). So I know it is my C# code that is the problem. I´ve tried using webrequest and I´ve also tried changing the Media type to application/Json and application/x-www-form-urlencoded



 protected void Page_Load(object sender, EventArgs e)


string Error = Request.QueryString["error"];

string Code = Request.QueryString["code"];
if (Error != null)
else if (Code != null)


string UserId = Request.QueryString["state"];
int Id = Convert.ToInt32(UserId);
string AccessToken = string.Empty;
string RefreshToken = ExchangeAuthorizationCode(Id, Code, out AccessToken);
string Url = "Authorize.aspx?UserId=" + UserId;
Response.Redirect(Url, true);


private string ExchangeAuthorizationCode(int userId, string code, out string accessToken)

string baseurl = "https://accounts.google.com/o/oauth2/token";
accessToken = string.Empty;
string ClientSecret = ConfigurationManager.AppSettings["ClientSecrete"];
string ClientId = ConfigurationManager.AppSettings["ClientId"];

string RedirectUrl = "http://localhost:64716/GoogleCallBack.aspx";

using (var client = new HttpClient())

client.BaseAddress = new Uri(baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/Json"));

var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("Code", code));
nvc.Add(new KeyValuePair<string, string>("Client_id", ClientId));
nvc.Add(new KeyValuePair<string, string>("Client_secret", ClientSecret));
nvc.Add(new KeyValuePair<string, string>("Redirect_uri", RedirectUrl));
nvc.Add(new KeyValuePair<string, string>("Grant_type", "authorization_code"));
nvc.Add(new KeyValuePair<string, string>("access_type", "offline"));

var req = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress) Content = new FormUrlEncodedContent(nvc) ;
var resres = client.SendAsync(req).Result;

return "temp";






I want my response to be statuscode 200 with an access_token from google (Like it does in Postman)










share|improve this question
























  • Ive not seen oauth tokens tried to be sent like this. Do your headers match the postman ones?

    – BugFinder
    Mar 28 at 10:58











  • In this particular example no, in Postman i use application/x-www-form-urlencoded instead of application/json but I have tried adding that too. It did not solve my problem.

    – Rawmouse
    Mar 28 at 12:03













1












1








1


0






I´m trying to learn how to implement Googles Oauth2 SSO login function. So far I´ve gotten to the point where everything works except when I try to send a request to "https://accounts.google.com/o/oauth2/token" using REST in C# to get the Access_code/Token. I´ve registered my localhost and the corresponding port on google and I´ve managed to get my POST request to work in POSTMAN however when i try sending a request in C# my HttpRequestMessage returns 400 bad request.



First I have an Authorization.aspx page that runs a command that redirects the users to googles authorization page where the user login and then gets redirected to my page http://localhost:64716/GoogleCallBack.aspx which picks up the response. In the page it picks up the authorization code and tries to send a POST request to the base URL. I´ve tried running it in POSTMAN where it works (although only with a new authorization code). So I know it is my C# code that is the problem. I´ve tried using webrequest and I´ve also tried changing the Media type to application/Json and application/x-www-form-urlencoded



 protected void Page_Load(object sender, EventArgs e)


string Error = Request.QueryString["error"];

string Code = Request.QueryString["code"];
if (Error != null)
else if (Code != null)


string UserId = Request.QueryString["state"];
int Id = Convert.ToInt32(UserId);
string AccessToken = string.Empty;
string RefreshToken = ExchangeAuthorizationCode(Id, Code, out AccessToken);
string Url = "Authorize.aspx?UserId=" + UserId;
Response.Redirect(Url, true);


private string ExchangeAuthorizationCode(int userId, string code, out string accessToken)

string baseurl = "https://accounts.google.com/o/oauth2/token";
accessToken = string.Empty;
string ClientSecret = ConfigurationManager.AppSettings["ClientSecrete"];
string ClientId = ConfigurationManager.AppSettings["ClientId"];

string RedirectUrl = "http://localhost:64716/GoogleCallBack.aspx";

using (var client = new HttpClient())

client.BaseAddress = new Uri(baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/Json"));

var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("Code", code));
nvc.Add(new KeyValuePair<string, string>("Client_id", ClientId));
nvc.Add(new KeyValuePair<string, string>("Client_secret", ClientSecret));
nvc.Add(new KeyValuePair<string, string>("Redirect_uri", RedirectUrl));
nvc.Add(new KeyValuePair<string, string>("Grant_type", "authorization_code"));
nvc.Add(new KeyValuePair<string, string>("access_type", "offline"));

var req = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress) Content = new FormUrlEncodedContent(nvc) ;
var resres = client.SendAsync(req).Result;

return "temp";






I want my response to be statuscode 200 with an access_token from google (Like it does in Postman)










share|improve this question














I´m trying to learn how to implement Googles Oauth2 SSO login function. So far I´ve gotten to the point where everything works except when I try to send a request to "https://accounts.google.com/o/oauth2/token" using REST in C# to get the Access_code/Token. I´ve registered my localhost and the corresponding port on google and I´ve managed to get my POST request to work in POSTMAN however when i try sending a request in C# my HttpRequestMessage returns 400 bad request.



First I have an Authorization.aspx page that runs a command that redirects the users to googles authorization page where the user login and then gets redirected to my page http://localhost:64716/GoogleCallBack.aspx which picks up the response. In the page it picks up the authorization code and tries to send a POST request to the base URL. I´ve tried running it in POSTMAN where it works (although only with a new authorization code). So I know it is my C# code that is the problem. I´ve tried using webrequest and I´ve also tried changing the Media type to application/Json and application/x-www-form-urlencoded



 protected void Page_Load(object sender, EventArgs e)


string Error = Request.QueryString["error"];

string Code = Request.QueryString["code"];
if (Error != null)
else if (Code != null)


string UserId = Request.QueryString["state"];
int Id = Convert.ToInt32(UserId);
string AccessToken = string.Empty;
string RefreshToken = ExchangeAuthorizationCode(Id, Code, out AccessToken);
string Url = "Authorize.aspx?UserId=" + UserId;
Response.Redirect(Url, true);


private string ExchangeAuthorizationCode(int userId, string code, out string accessToken)

string baseurl = "https://accounts.google.com/o/oauth2/token";
accessToken = string.Empty;
string ClientSecret = ConfigurationManager.AppSettings["ClientSecrete"];
string ClientId = ConfigurationManager.AppSettings["ClientId"];

string RedirectUrl = "http://localhost:64716/GoogleCallBack.aspx";

using (var client = new HttpClient())

client.BaseAddress = new Uri(baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/Json"));

var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("Code", code));
nvc.Add(new KeyValuePair<string, string>("Client_id", ClientId));
nvc.Add(new KeyValuePair<string, string>("Client_secret", ClientSecret));
nvc.Add(new KeyValuePair<string, string>("Redirect_uri", RedirectUrl));
nvc.Add(new KeyValuePair<string, string>("Grant_type", "authorization_code"));
nvc.Add(new KeyValuePair<string, string>("access_type", "offline"));

var req = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress) Content = new FormUrlEncodedContent(nvc) ;
var resres = client.SendAsync(req).Result;

return "temp";






I want my response to be statuscode 200 with an access_token from google (Like it does in Postman)







c# asp.net rest oauth-2.0






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 28 at 10:53









RawmouseRawmouse

195 bronze badges




195 bronze badges















  • Ive not seen oauth tokens tried to be sent like this. Do your headers match the postman ones?

    – BugFinder
    Mar 28 at 10:58











  • In this particular example no, in Postman i use application/x-www-form-urlencoded instead of application/json but I have tried adding that too. It did not solve my problem.

    – Rawmouse
    Mar 28 at 12:03

















  • Ive not seen oauth tokens tried to be sent like this. Do your headers match the postman ones?

    – BugFinder
    Mar 28 at 10:58











  • In this particular example no, in Postman i use application/x-www-form-urlencoded instead of application/json but I have tried adding that too. It did not solve my problem.

    – Rawmouse
    Mar 28 at 12:03
















Ive not seen oauth tokens tried to be sent like this. Do your headers match the postman ones?

– BugFinder
Mar 28 at 10:58





Ive not seen oauth tokens tried to be sent like this. Do your headers match the postman ones?

– BugFinder
Mar 28 at 10:58













In this particular example no, in Postman i use application/x-www-form-urlencoded instead of application/json but I have tried adding that too. It did not solve my problem.

– Rawmouse
Mar 28 at 12:03





In this particular example no, in Postman i use application/x-www-form-urlencoded instead of application/json but I have tried adding that too. It did not solve my problem.

– Rawmouse
Mar 28 at 12:03












1 Answer
1






active

oldest

votes


















0
















[resolved] This is what I did (With the help from a few friends)



  1. Changed Headers to JSON


  2. Moved the Base URI to PostAsync()



  3. Once I had change all that I could see that the error was in the redirect_Uri and I then changed it to match the one in postman. And now it works



    protected void Page_Load(object sender, EventArgs e)

    //you will get this, when any error will occur while authorization otherwise null
    string Error = Request.QueryString["error"];
    //authorization code after successful authorization
    string Code = Request.QueryString["code"];
    if (Error != null)
    else if (Code != null)

    //Remember, we have set userid in State
    string UserId = Request.QueryString["state"];
    //Get AccessToken
    int Id = Convert.ToInt32(UserId);
    string AccessToken = string.Empty;
    string RefreshToken = ExchangeAuthorizationCode(Id, Code, out AccessToken);
    //saving refresh token in database
    SaveRefreshToken(Id, RefreshToken);
    //Get Email Id of the authorized user
    string EmailId = FetchEmailId(AccessToken);
    //Saving Email Id
    SaveEmailId(UserId, EmailId);
    //Redirect the user to Authorize.aspx with user id
    string Url = "Authorize.aspx?UserId=" + UserId;
    Response.Redirect(Url, true);



    private string ExchangeAuthorizationCode(int userId, string code, out string accessToken)

    string baseurl = "https://accounts.google.com/o/oauth2/token";
    accessToken = string.Empty;
    string ClientSecret = ConfigurationManager.AppSettings["ClientSecrete"];
    string ClientId = ConfigurationManager.AppSettings["ClientId"];
    // //get this value by opening your web app in browser.
    string RedirectUrl = "http://localhost:64716/GoogleCallback.aspx"; //I changed this to match the one in Postman

    using (var client = new HttpClient())

    //client.BaseAddress = new Uri("https://accounts.google.com/o/oauth2"); //I replaced the Uri to "var result = client.PostAsync("https://accounts.google.com/o/oauth2/token", nvc).Result;"
    client.DefaultRequestHeaders.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // I made this JSON
    // I removed this "client.DefaultRequestHeaders.Add("Content-Type", "application/x-www-form-urlencoded");"

    var nvc = new FormUrlEncodedContent(new[]
    new KeyValuePair<string, string>("grant_type", "authorization_code"),
    new KeyValuePair<string, string>("code", code),
    new KeyValuePair<string, string>("client_id", ClientId),
    new KeyValuePair<string, string>("client_secret", ClientSecret),
    new KeyValuePair<string, string>("redirect_uri", RedirectUrl),
    new KeyValuePair<string, string>("access_type", "offline")
    );

    var result = client.PostAsync("https://accounts.google.com/o/oauth2/token", nvc).Result;

    var resultContent = result.Content.ReadAsStringAsync();

    var tokenResponse = JsonConvert.DeserializeObject<Authorization_request_body>(resultContent.ToString());

    return "temp";










share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );














    draft saved

    draft discarded
















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55395793%2fhow-to-fix-bad-request-error-when-sending-rest-request-to-google-oauth2-sso-in%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0
















    [resolved] This is what I did (With the help from a few friends)



    1. Changed Headers to JSON


    2. Moved the Base URI to PostAsync()



    3. Once I had change all that I could see that the error was in the redirect_Uri and I then changed it to match the one in postman. And now it works



      protected void Page_Load(object sender, EventArgs e)

      //you will get this, when any error will occur while authorization otherwise null
      string Error = Request.QueryString["error"];
      //authorization code after successful authorization
      string Code = Request.QueryString["code"];
      if (Error != null)
      else if (Code != null)

      //Remember, we have set userid in State
      string UserId = Request.QueryString["state"];
      //Get AccessToken
      int Id = Convert.ToInt32(UserId);
      string AccessToken = string.Empty;
      string RefreshToken = ExchangeAuthorizationCode(Id, Code, out AccessToken);
      //saving refresh token in database
      SaveRefreshToken(Id, RefreshToken);
      //Get Email Id of the authorized user
      string EmailId = FetchEmailId(AccessToken);
      //Saving Email Id
      SaveEmailId(UserId, EmailId);
      //Redirect the user to Authorize.aspx with user id
      string Url = "Authorize.aspx?UserId=" + UserId;
      Response.Redirect(Url, true);



      private string ExchangeAuthorizationCode(int userId, string code, out string accessToken)

      string baseurl = "https://accounts.google.com/o/oauth2/token";
      accessToken = string.Empty;
      string ClientSecret = ConfigurationManager.AppSettings["ClientSecrete"];
      string ClientId = ConfigurationManager.AppSettings["ClientId"];
      // //get this value by opening your web app in browser.
      string RedirectUrl = "http://localhost:64716/GoogleCallback.aspx"; //I changed this to match the one in Postman

      using (var client = new HttpClient())

      //client.BaseAddress = new Uri("https://accounts.google.com/o/oauth2"); //I replaced the Uri to "var result = client.PostAsync("https://accounts.google.com/o/oauth2/token", nvc).Result;"
      client.DefaultRequestHeaders.Clear();
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // I made this JSON
      // I removed this "client.DefaultRequestHeaders.Add("Content-Type", "application/x-www-form-urlencoded");"

      var nvc = new FormUrlEncodedContent(new[]
      new KeyValuePair<string, string>("grant_type", "authorization_code"),
      new KeyValuePair<string, string>("code", code),
      new KeyValuePair<string, string>("client_id", ClientId),
      new KeyValuePair<string, string>("client_secret", ClientSecret),
      new KeyValuePair<string, string>("redirect_uri", RedirectUrl),
      new KeyValuePair<string, string>("access_type", "offline")
      );

      var result = client.PostAsync("https://accounts.google.com/o/oauth2/token", nvc).Result;

      var resultContent = result.Content.ReadAsStringAsync();

      var tokenResponse = JsonConvert.DeserializeObject<Authorization_request_body>(resultContent.ToString());

      return "temp";










    share|improve this answer





























      0
















      [resolved] This is what I did (With the help from a few friends)



      1. Changed Headers to JSON


      2. Moved the Base URI to PostAsync()



      3. Once I had change all that I could see that the error was in the redirect_Uri and I then changed it to match the one in postman. And now it works



        protected void Page_Load(object sender, EventArgs e)

        //you will get this, when any error will occur while authorization otherwise null
        string Error = Request.QueryString["error"];
        //authorization code after successful authorization
        string Code = Request.QueryString["code"];
        if (Error != null)
        else if (Code != null)

        //Remember, we have set userid in State
        string UserId = Request.QueryString["state"];
        //Get AccessToken
        int Id = Convert.ToInt32(UserId);
        string AccessToken = string.Empty;
        string RefreshToken = ExchangeAuthorizationCode(Id, Code, out AccessToken);
        //saving refresh token in database
        SaveRefreshToken(Id, RefreshToken);
        //Get Email Id of the authorized user
        string EmailId = FetchEmailId(AccessToken);
        //Saving Email Id
        SaveEmailId(UserId, EmailId);
        //Redirect the user to Authorize.aspx with user id
        string Url = "Authorize.aspx?UserId=" + UserId;
        Response.Redirect(Url, true);



        private string ExchangeAuthorizationCode(int userId, string code, out string accessToken)

        string baseurl = "https://accounts.google.com/o/oauth2/token";
        accessToken = string.Empty;
        string ClientSecret = ConfigurationManager.AppSettings["ClientSecrete"];
        string ClientId = ConfigurationManager.AppSettings["ClientId"];
        // //get this value by opening your web app in browser.
        string RedirectUrl = "http://localhost:64716/GoogleCallback.aspx"; //I changed this to match the one in Postman

        using (var client = new HttpClient())

        //client.BaseAddress = new Uri("https://accounts.google.com/o/oauth2"); //I replaced the Uri to "var result = client.PostAsync("https://accounts.google.com/o/oauth2/token", nvc).Result;"
        client.DefaultRequestHeaders.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // I made this JSON
        // I removed this "client.DefaultRequestHeaders.Add("Content-Type", "application/x-www-form-urlencoded");"

        var nvc = new FormUrlEncodedContent(new[]
        new KeyValuePair<string, string>("grant_type", "authorization_code"),
        new KeyValuePair<string, string>("code", code),
        new KeyValuePair<string, string>("client_id", ClientId),
        new KeyValuePair<string, string>("client_secret", ClientSecret),
        new KeyValuePair<string, string>("redirect_uri", RedirectUrl),
        new KeyValuePair<string, string>("access_type", "offline")
        );

        var result = client.PostAsync("https://accounts.google.com/o/oauth2/token", nvc).Result;

        var resultContent = result.Content.ReadAsStringAsync();

        var tokenResponse = JsonConvert.DeserializeObject<Authorization_request_body>(resultContent.ToString());

        return "temp";










      share|improve this answer



























        0














        0










        0









        [resolved] This is what I did (With the help from a few friends)



        1. Changed Headers to JSON


        2. Moved the Base URI to PostAsync()



        3. Once I had change all that I could see that the error was in the redirect_Uri and I then changed it to match the one in postman. And now it works



          protected void Page_Load(object sender, EventArgs e)

          //you will get this, when any error will occur while authorization otherwise null
          string Error = Request.QueryString["error"];
          //authorization code after successful authorization
          string Code = Request.QueryString["code"];
          if (Error != null)
          else if (Code != null)

          //Remember, we have set userid in State
          string UserId = Request.QueryString["state"];
          //Get AccessToken
          int Id = Convert.ToInt32(UserId);
          string AccessToken = string.Empty;
          string RefreshToken = ExchangeAuthorizationCode(Id, Code, out AccessToken);
          //saving refresh token in database
          SaveRefreshToken(Id, RefreshToken);
          //Get Email Id of the authorized user
          string EmailId = FetchEmailId(AccessToken);
          //Saving Email Id
          SaveEmailId(UserId, EmailId);
          //Redirect the user to Authorize.aspx with user id
          string Url = "Authorize.aspx?UserId=" + UserId;
          Response.Redirect(Url, true);



          private string ExchangeAuthorizationCode(int userId, string code, out string accessToken)

          string baseurl = "https://accounts.google.com/o/oauth2/token";
          accessToken = string.Empty;
          string ClientSecret = ConfigurationManager.AppSettings["ClientSecrete"];
          string ClientId = ConfigurationManager.AppSettings["ClientId"];
          // //get this value by opening your web app in browser.
          string RedirectUrl = "http://localhost:64716/GoogleCallback.aspx"; //I changed this to match the one in Postman

          using (var client = new HttpClient())

          //client.BaseAddress = new Uri("https://accounts.google.com/o/oauth2"); //I replaced the Uri to "var result = client.PostAsync("https://accounts.google.com/o/oauth2/token", nvc).Result;"
          client.DefaultRequestHeaders.Clear();
          client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // I made this JSON
          // I removed this "client.DefaultRequestHeaders.Add("Content-Type", "application/x-www-form-urlencoded");"

          var nvc = new FormUrlEncodedContent(new[]
          new KeyValuePair<string, string>("grant_type", "authorization_code"),
          new KeyValuePair<string, string>("code", code),
          new KeyValuePair<string, string>("client_id", ClientId),
          new KeyValuePair<string, string>("client_secret", ClientSecret),
          new KeyValuePair<string, string>("redirect_uri", RedirectUrl),
          new KeyValuePair<string, string>("access_type", "offline")
          );

          var result = client.PostAsync("https://accounts.google.com/o/oauth2/token", nvc).Result;

          var resultContent = result.Content.ReadAsStringAsync();

          var tokenResponse = JsonConvert.DeserializeObject<Authorization_request_body>(resultContent.ToString());

          return "temp";










        share|improve this answer













        [resolved] This is what I did (With the help from a few friends)



        1. Changed Headers to JSON


        2. Moved the Base URI to PostAsync()



        3. Once I had change all that I could see that the error was in the redirect_Uri and I then changed it to match the one in postman. And now it works



          protected void Page_Load(object sender, EventArgs e)

          //you will get this, when any error will occur while authorization otherwise null
          string Error = Request.QueryString["error"];
          //authorization code after successful authorization
          string Code = Request.QueryString["code"];
          if (Error != null)
          else if (Code != null)

          //Remember, we have set userid in State
          string UserId = Request.QueryString["state"];
          //Get AccessToken
          int Id = Convert.ToInt32(UserId);
          string AccessToken = string.Empty;
          string RefreshToken = ExchangeAuthorizationCode(Id, Code, out AccessToken);
          //saving refresh token in database
          SaveRefreshToken(Id, RefreshToken);
          //Get Email Id of the authorized user
          string EmailId = FetchEmailId(AccessToken);
          //Saving Email Id
          SaveEmailId(UserId, EmailId);
          //Redirect the user to Authorize.aspx with user id
          string Url = "Authorize.aspx?UserId=" + UserId;
          Response.Redirect(Url, true);



          private string ExchangeAuthorizationCode(int userId, string code, out string accessToken)

          string baseurl = "https://accounts.google.com/o/oauth2/token";
          accessToken = string.Empty;
          string ClientSecret = ConfigurationManager.AppSettings["ClientSecrete"];
          string ClientId = ConfigurationManager.AppSettings["ClientId"];
          // //get this value by opening your web app in browser.
          string RedirectUrl = "http://localhost:64716/GoogleCallback.aspx"; //I changed this to match the one in Postman

          using (var client = new HttpClient())

          //client.BaseAddress = new Uri("https://accounts.google.com/o/oauth2"); //I replaced the Uri to "var result = client.PostAsync("https://accounts.google.com/o/oauth2/token", nvc).Result;"
          client.DefaultRequestHeaders.Clear();
          client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // I made this JSON
          // I removed this "client.DefaultRequestHeaders.Add("Content-Type", "application/x-www-form-urlencoded");"

          var nvc = new FormUrlEncodedContent(new[]
          new KeyValuePair<string, string>("grant_type", "authorization_code"),
          new KeyValuePair<string, string>("code", code),
          new KeyValuePair<string, string>("client_id", ClientId),
          new KeyValuePair<string, string>("client_secret", ClientSecret),
          new KeyValuePair<string, string>("redirect_uri", RedirectUrl),
          new KeyValuePair<string, string>("access_type", "offline")
          );

          var result = client.PostAsync("https://accounts.google.com/o/oauth2/token", nvc).Result;

          var resultContent = result.Content.ReadAsStringAsync();

          var tokenResponse = JsonConvert.DeserializeObject<Authorization_request_body>(resultContent.ToString());

          return "temp";











        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 29 at 8:50









        RawmouseRawmouse

        195 bronze badges




        195 bronze badges



















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.




















            draft saved

            draft discarded















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55395793%2fhow-to-fix-bad-request-error-when-sending-rest-request-to-google-oauth2-sso-in%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript