How to get access token for google oauth?Access token request format for google plus in C# web appHow do I enumerate an enum in C#?How do I format a Microsoft JSON date?Is there a link to the “latest” jQuery library on Google APIs?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?How is OAuth 2 different from OAuth 1?How does OAuth 2 protect against things like replay attacks using the Security Token?Failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request - OAuth 2.0 POST400 Bad Request when sending http post request to get token from auth code?Oauth : Google Api : access deniedCheck the “grant_type” parameter

How can I kill my goat?

What do you call a flexible diving platform?

What is this 4 sharp symbol and what does it mean?

Why is the Apollo LEM ladder so far from the ground?

Why didn’t Christianity spread southwards from Ethiopia in the Middle Ages?

How many oliphaunts died in all of the Lord of the Rings battles?

Anti-cheating: should there be a limit to a number of toilet breaks per game per player?

How to store my pliers and wire cutters on my desk?

Can you place a support header in the ceiling?

Strange pattern-matching: is it correct?

ECDSA: Why is SigningKey shorter than VerifyingKey

Compound Word Neologism

Is it error of law to judge on less relevant case law when there is much more relevant one?

Can a US President, after impeachment and removal, be re-elected or re-appointed?

Why not notify faculty candidates of the position being filled?

How can Paypal know my card is being used in another account?

reconstruction filter - How does it actually work?

What language is Raven using for her attack in the new 52?

If Trump gets impeached, how long would Pence be president?

Finding the Maximum of a Continuous Function over a Closed Interval

Are there any unpublished Iain M. Banks short stories?

Irreducible factors of primitive permutation group representation

How do I learn to recognise what is worth publishing

Why does the Eurostar not show youth pricing?



How to get access token for google oauth?


Access token request format for google plus in C# web appHow do I enumerate an enum in C#?How do I format a Microsoft JSON date?Is there a link to the “latest” jQuery library on Google APIs?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?How is OAuth 2 different from OAuth 1?How does OAuth 2 protect against things like replay attacks using the Security Token?Failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request - OAuth 2.0 POST400 Bad Request when sending http post request to get token from auth code?Oauth : Google Api : access deniedCheck the “grant_type” parameter






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








11















I am using C# (ASP.NET). I want to use Google OAuth for accessing the user profile detail in my app. I successfully got the authorization code but having a problem in getting the access token.
I prefer the Google tutorials. In tutorial, I read that I have to send the request and get the response from google. For that, I use System.Net.HttpWebRequest/HttpWebResponse (am I going in the right way). I have used this code...



byte[] buffer = Encoding.ASCII.GetBytes("?code=" + code + "&client_id=xxx&client_secret=xxx&redirect_uri=xxxx&grant_type=authorization_code");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://accounts.google.com");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = buffer.Length;

Stream strm = req.GetRequestStream();
strm.Write(buffer, 0, buffer.Length);
strm.Close();

HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Response.Write(((HttpWebResponse)resp).StatusDescription);


But, I got the error:




The remote server returned an error: (405) Method Not Allowed.




Update: Here variable code is authorization code.










share|improve this question





















  • 1





    Why don't you use code.google.com/p/google-api-dotnet-client/wiki/OAuth2

    – user854301
    Aug 6 '12 at 17:54











  • @user854301 I can refer this but I wanted to know that using of HttpWebRequest/Response is correct or not? Can I send the request to google from HttpWebRequest.

    – Sagar
    Aug 6 '12 at 19:39











  • What is "code" in ur buffer??

    – Apoorva
    Oct 11 '12 at 6:17











  • @Apoorva It is a authorisation code.

    – Sagar
    Oct 11 '12 at 16:55











  • How to get authorisation code...can you please tell me i don't know about it..

    – user4736499
    Jul 10 '15 at 11:33

















11















I am using C# (ASP.NET). I want to use Google OAuth for accessing the user profile detail in my app. I successfully got the authorization code but having a problem in getting the access token.
I prefer the Google tutorials. In tutorial, I read that I have to send the request and get the response from google. For that, I use System.Net.HttpWebRequest/HttpWebResponse (am I going in the right way). I have used this code...



byte[] buffer = Encoding.ASCII.GetBytes("?code=" + code + "&client_id=xxx&client_secret=xxx&redirect_uri=xxxx&grant_type=authorization_code");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://accounts.google.com");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = buffer.Length;

Stream strm = req.GetRequestStream();
strm.Write(buffer, 0, buffer.Length);
strm.Close();

HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Response.Write(((HttpWebResponse)resp).StatusDescription);


But, I got the error:




The remote server returned an error: (405) Method Not Allowed.




Update: Here variable code is authorization code.










share|improve this question





















  • 1





    Why don't you use code.google.com/p/google-api-dotnet-client/wiki/OAuth2

    – user854301
    Aug 6 '12 at 17:54











  • @user854301 I can refer this but I wanted to know that using of HttpWebRequest/Response is correct or not? Can I send the request to google from HttpWebRequest.

    – Sagar
    Aug 6 '12 at 19:39











  • What is "code" in ur buffer??

    – Apoorva
    Oct 11 '12 at 6:17











  • @Apoorva It is a authorisation code.

    – Sagar
    Oct 11 '12 at 16:55











  • How to get authorisation code...can you please tell me i don't know about it..

    – user4736499
    Jul 10 '15 at 11:33













11












11








11


5






I am using C# (ASP.NET). I want to use Google OAuth for accessing the user profile detail in my app. I successfully got the authorization code but having a problem in getting the access token.
I prefer the Google tutorials. In tutorial, I read that I have to send the request and get the response from google. For that, I use System.Net.HttpWebRequest/HttpWebResponse (am I going in the right way). I have used this code...



byte[] buffer = Encoding.ASCII.GetBytes("?code=" + code + "&client_id=xxx&client_secret=xxx&redirect_uri=xxxx&grant_type=authorization_code");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://accounts.google.com");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = buffer.Length;

Stream strm = req.GetRequestStream();
strm.Write(buffer, 0, buffer.Length);
strm.Close();

HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Response.Write(((HttpWebResponse)resp).StatusDescription);


But, I got the error:




The remote server returned an error: (405) Method Not Allowed.




Update: Here variable code is authorization code.










share|improve this question
















I am using C# (ASP.NET). I want to use Google OAuth for accessing the user profile detail in my app. I successfully got the authorization code but having a problem in getting the access token.
I prefer the Google tutorials. In tutorial, I read that I have to send the request and get the response from google. For that, I use System.Net.HttpWebRequest/HttpWebResponse (am I going in the right way). I have used this code...



byte[] buffer = Encoding.ASCII.GetBytes("?code=" + code + "&client_id=xxx&client_secret=xxx&redirect_uri=xxxx&grant_type=authorization_code");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://accounts.google.com");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = buffer.Length;

Stream strm = req.GetRequestStream();
strm.Write(buffer, 0, buffer.Length);
strm.Close();

HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Response.Write(((HttpWebResponse)resp).StatusDescription);


But, I got the error:




The remote server returned an error: (405) Method Not Allowed.




Update: Here variable code is authorization code.







c# asp.net google-api oauth-2.0






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 19:35







Sagar

















asked Aug 6 '12 at 17:46









SagarSagar

1,5794 gold badges16 silver badges29 bronze badges




1,5794 gold badges16 silver badges29 bronze badges










  • 1





    Why don't you use code.google.com/p/google-api-dotnet-client/wiki/OAuth2

    – user854301
    Aug 6 '12 at 17:54











  • @user854301 I can refer this but I wanted to know that using of HttpWebRequest/Response is correct or not? Can I send the request to google from HttpWebRequest.

    – Sagar
    Aug 6 '12 at 19:39











  • What is "code" in ur buffer??

    – Apoorva
    Oct 11 '12 at 6:17











  • @Apoorva It is a authorisation code.

    – Sagar
    Oct 11 '12 at 16:55











  • How to get authorisation code...can you please tell me i don't know about it..

    – user4736499
    Jul 10 '15 at 11:33












  • 1





    Why don't you use code.google.com/p/google-api-dotnet-client/wiki/OAuth2

    – user854301
    Aug 6 '12 at 17:54











  • @user854301 I can refer this but I wanted to know that using of HttpWebRequest/Response is correct or not? Can I send the request to google from HttpWebRequest.

    – Sagar
    Aug 6 '12 at 19:39











  • What is "code" in ur buffer??

    – Apoorva
    Oct 11 '12 at 6:17











  • @Apoorva It is a authorisation code.

    – Sagar
    Oct 11 '12 at 16:55











  • How to get authorisation code...can you please tell me i don't know about it..

    – user4736499
    Jul 10 '15 at 11:33







1




1





Why don't you use code.google.com/p/google-api-dotnet-client/wiki/OAuth2

– user854301
Aug 6 '12 at 17:54





Why don't you use code.google.com/p/google-api-dotnet-client/wiki/OAuth2

– user854301
Aug 6 '12 at 17:54













@user854301 I can refer this but I wanted to know that using of HttpWebRequest/Response is correct or not? Can I send the request to google from HttpWebRequest.

– Sagar
Aug 6 '12 at 19:39





@user854301 I can refer this but I wanted to know that using of HttpWebRequest/Response is correct or not? Can I send the request to google from HttpWebRequest.

– Sagar
Aug 6 '12 at 19:39













What is "code" in ur buffer??

– Apoorva
Oct 11 '12 at 6:17





What is "code" in ur buffer??

– Apoorva
Oct 11 '12 at 6:17













@Apoorva It is a authorisation code.

– Sagar
Oct 11 '12 at 16:55





@Apoorva It is a authorisation code.

– Sagar
Oct 11 '12 at 16:55













How to get authorisation code...can you please tell me i don't know about it..

– user4736499
Jul 10 '15 at 11:33





How to get authorisation code...can you please tell me i don't know about it..

– user4736499
Jul 10 '15 at 11:33












5 Answers
5






active

oldest

votes


















8














I think you are sending the POST request to the wrong endpoint, the correct one is https://accounts.google.com/o/oauth2/token






share|improve this answer




















  • 2





    I use this, but it shows me other error. Now error is The remote server returned an error: (400) Bad Request. Where am I going wrong?

    – Sagar
    Aug 8 '12 at 18:44











  • Drill down into the details of the exception, the complete error message will tell you what is wrong with your request

    – Claudio Cherubino
    Aug 8 '12 at 18:58


















4














As I had similar problems in the process of implementing Google auth, I will post the code that works.. The last mentioned problem: error (400) Bad request could be caused by leading '?' in the above code..



 string codeClient = "code="+ t +"&client_id=number.apps.googleusercontent.com&";
string secretUri = "client_secret=yoursecret&" + "redirect_uri=path&"
+ "grant_type=authorization_code";
postString = codeClient + secretUri;

string url = "https://accounts.google.com/o/oauth2/token";

HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url.ToString());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";

UTF8Encoding utfenc = new UTF8Encoding();
byte[] bytes = utfenc.GetBytes(postString);
Stream os = null;
try

request.ContentLength = bytes.Length;
os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length);

catch


try
{
HttpWebResponse webResponse = (HttpWebResponse) request.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(responseStream);
result = responseStreamReader.ReadToEnd();//parse token from result





share|improve this answer



























  • what is "t" used for code..and how to get it..

    – user4736499
    Jul 10 '15 at 11:34












  • t the initial authorization code...

    – Martin Pfeffer
    Sep 25 '15 at 19:09











  • It still says Bad Request with this code also

    – Sahil Bhatia
    Jun 27 '17 at 12:20











  • @Sahil, make sure that oauth url is the valid one. Note that I used this code snippet almost 5 years ago.

    – Neno
    Jun 28 '17 at 9:00











  • thanks, it looks like working fine now.

    – Sahil Bhatia
    Jun 28 '17 at 17:07


















2














My code is working, I have done mistakes in above two lines. It should be like this



byte[] buffer = Encoding.ASCII.GetBytes("code=" + code + "&client_id=xxx&client_secret=xxx&redirect_uri=xxxx&grant_type=authorization_code");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");


Remaining code is correct.






share|improve this answer




















  • 2





    What is the Code variable in your code..

    – Devi Prasad
    Jul 10 '15 at 4:00











  • @Viktor: I notice your client id and client secret are both included in the buffer. My hosted website does not have SSL. Do you know if Google will accept my web request from a non SSL connection? Obviously, it would not be safe, and someone could snipe my credentials, but I don't know a way around it.

    – jp2code
    Sep 8 '15 at 22:03


















0














The original request seems to be somewhat outdated. But I found that the Google's code examples contain lots of "Best Practices" housekeeping code that's hard to separate from the essential operations.



I recently published a document that represents all the REST operations as curl commands. It's hard to be conversant in every language, but curl seems universal. Most people know it- otherwise, it's pretty easy to grasp. In my curl examples, the -d flag indicates a POST operation. Otherwise, the parameters are appended to the URL.



http://www.tqis.com/eloquency/googlecalendar.htm






share|improve this answer
































    0














    public string ReceiveTokenGmail(string code, string GoogleWebAppClientID, string GoogleWebAppClientSecret, string RedirectUrl)

    string postString = "code=" + code + "&client_id=" + GoogleWebAppClientID + @"&client_secret=" + GoogleWebAppClientSecret + "&redirect_uri=" + RedirectUrl;

    string url = "https://accounts.google.com/o/oauth2/token";

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";

    UTF8Encoding utfenc = new UTF8Encoding();
    byte[] bytes = utfenc.GetBytes(postString);
    Stream os = null;
    try

    request.ContentLength = bytes.Length;
    os = request.GetRequestStream();
    os.Write(bytes, 0, bytes.Length);

    catch

    string result = "";

    HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
    Stream responseStream = webResponse.GetResponseStream();
    StreamReader responseStreamReader = new StreamReader(responseStream);
    result = responseStreamReader.ReadToEnd();

    return result;






    share|improve this answer

























    • how do I get the Authentication code from google?. I wanted to use your code so I dont have to use key.json file and just use an app config for my client id and client secret.If you could share how to get the authorization code, that would be awesome.

      – CyberNinja
      Jul 5 '17 at 12:21













    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/3.0/"u003ecc by-sa 3.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%2f11833281%2fhow-to-get-access-token-for-google-oauth%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    5 Answers
    5






    active

    oldest

    votes








    5 Answers
    5






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    8














    I think you are sending the POST request to the wrong endpoint, the correct one is https://accounts.google.com/o/oauth2/token






    share|improve this answer




















    • 2





      I use this, but it shows me other error. Now error is The remote server returned an error: (400) Bad Request. Where am I going wrong?

      – Sagar
      Aug 8 '12 at 18:44











    • Drill down into the details of the exception, the complete error message will tell you what is wrong with your request

      – Claudio Cherubino
      Aug 8 '12 at 18:58















    8














    I think you are sending the POST request to the wrong endpoint, the correct one is https://accounts.google.com/o/oauth2/token






    share|improve this answer




















    • 2





      I use this, but it shows me other error. Now error is The remote server returned an error: (400) Bad Request. Where am I going wrong?

      – Sagar
      Aug 8 '12 at 18:44











    • Drill down into the details of the exception, the complete error message will tell you what is wrong with your request

      – Claudio Cherubino
      Aug 8 '12 at 18:58













    8












    8








    8







    I think you are sending the POST request to the wrong endpoint, the correct one is https://accounts.google.com/o/oauth2/token






    share|improve this answer













    I think you are sending the POST request to the wrong endpoint, the correct one is https://accounts.google.com/o/oauth2/token







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Aug 6 '12 at 20:05









    Claudio CherubinoClaudio Cherubino

    14k1 gold badge28 silver badges39 bronze badges




    14k1 gold badge28 silver badges39 bronze badges










    • 2





      I use this, but it shows me other error. Now error is The remote server returned an error: (400) Bad Request. Where am I going wrong?

      – Sagar
      Aug 8 '12 at 18:44











    • Drill down into the details of the exception, the complete error message will tell you what is wrong with your request

      – Claudio Cherubino
      Aug 8 '12 at 18:58












    • 2





      I use this, but it shows me other error. Now error is The remote server returned an error: (400) Bad Request. Where am I going wrong?

      – Sagar
      Aug 8 '12 at 18:44











    • Drill down into the details of the exception, the complete error message will tell you what is wrong with your request

      – Claudio Cherubino
      Aug 8 '12 at 18:58







    2




    2





    I use this, but it shows me other error. Now error is The remote server returned an error: (400) Bad Request. Where am I going wrong?

    – Sagar
    Aug 8 '12 at 18:44





    I use this, but it shows me other error. Now error is The remote server returned an error: (400) Bad Request. Where am I going wrong?

    – Sagar
    Aug 8 '12 at 18:44













    Drill down into the details of the exception, the complete error message will tell you what is wrong with your request

    – Claudio Cherubino
    Aug 8 '12 at 18:58





    Drill down into the details of the exception, the complete error message will tell you what is wrong with your request

    – Claudio Cherubino
    Aug 8 '12 at 18:58













    4














    As I had similar problems in the process of implementing Google auth, I will post the code that works.. The last mentioned problem: error (400) Bad request could be caused by leading '?' in the above code..



     string codeClient = "code="+ t +"&client_id=number.apps.googleusercontent.com&";
    string secretUri = "client_secret=yoursecret&" + "redirect_uri=path&"
    + "grant_type=authorization_code";
    postString = codeClient + secretUri;

    string url = "https://accounts.google.com/o/oauth2/token";

    HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url.ToString());
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";

    UTF8Encoding utfenc = new UTF8Encoding();
    byte[] bytes = utfenc.GetBytes(postString);
    Stream os = null;
    try

    request.ContentLength = bytes.Length;
    os = request.GetRequestStream();
    os.Write(bytes, 0, bytes.Length);

    catch


    try
    {
    HttpWebResponse webResponse = (HttpWebResponse) request.GetResponse();
    Stream responseStream = webResponse.GetResponseStream();
    StreamReader responseStreamReader = new StreamReader(responseStream);
    result = responseStreamReader.ReadToEnd();//parse token from result





    share|improve this answer



























    • what is "t" used for code..and how to get it..

      – user4736499
      Jul 10 '15 at 11:34












    • t the initial authorization code...

      – Martin Pfeffer
      Sep 25 '15 at 19:09











    • It still says Bad Request with this code also

      – Sahil Bhatia
      Jun 27 '17 at 12:20











    • @Sahil, make sure that oauth url is the valid one. Note that I used this code snippet almost 5 years ago.

      – Neno
      Jun 28 '17 at 9:00











    • thanks, it looks like working fine now.

      – Sahil Bhatia
      Jun 28 '17 at 17:07















    4














    As I had similar problems in the process of implementing Google auth, I will post the code that works.. The last mentioned problem: error (400) Bad request could be caused by leading '?' in the above code..



     string codeClient = "code="+ t +"&client_id=number.apps.googleusercontent.com&";
    string secretUri = "client_secret=yoursecret&" + "redirect_uri=path&"
    + "grant_type=authorization_code";
    postString = codeClient + secretUri;

    string url = "https://accounts.google.com/o/oauth2/token";

    HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url.ToString());
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";

    UTF8Encoding utfenc = new UTF8Encoding();
    byte[] bytes = utfenc.GetBytes(postString);
    Stream os = null;
    try

    request.ContentLength = bytes.Length;
    os = request.GetRequestStream();
    os.Write(bytes, 0, bytes.Length);

    catch


    try
    {
    HttpWebResponse webResponse = (HttpWebResponse) request.GetResponse();
    Stream responseStream = webResponse.GetResponseStream();
    StreamReader responseStreamReader = new StreamReader(responseStream);
    result = responseStreamReader.ReadToEnd();//parse token from result





    share|improve this answer



























    • what is "t" used for code..and how to get it..

      – user4736499
      Jul 10 '15 at 11:34












    • t the initial authorization code...

      – Martin Pfeffer
      Sep 25 '15 at 19:09











    • It still says Bad Request with this code also

      – Sahil Bhatia
      Jun 27 '17 at 12:20











    • @Sahil, make sure that oauth url is the valid one. Note that I used this code snippet almost 5 years ago.

      – Neno
      Jun 28 '17 at 9:00











    • thanks, it looks like working fine now.

      – Sahil Bhatia
      Jun 28 '17 at 17:07













    4












    4








    4







    As I had similar problems in the process of implementing Google auth, I will post the code that works.. The last mentioned problem: error (400) Bad request could be caused by leading '?' in the above code..



     string codeClient = "code="+ t +"&client_id=number.apps.googleusercontent.com&";
    string secretUri = "client_secret=yoursecret&" + "redirect_uri=path&"
    + "grant_type=authorization_code";
    postString = codeClient + secretUri;

    string url = "https://accounts.google.com/o/oauth2/token";

    HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url.ToString());
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";

    UTF8Encoding utfenc = new UTF8Encoding();
    byte[] bytes = utfenc.GetBytes(postString);
    Stream os = null;
    try

    request.ContentLength = bytes.Length;
    os = request.GetRequestStream();
    os.Write(bytes, 0, bytes.Length);

    catch


    try
    {
    HttpWebResponse webResponse = (HttpWebResponse) request.GetResponse();
    Stream responseStream = webResponse.GetResponseStream();
    StreamReader responseStreamReader = new StreamReader(responseStream);
    result = responseStreamReader.ReadToEnd();//parse token from result





    share|improve this answer















    As I had similar problems in the process of implementing Google auth, I will post the code that works.. The last mentioned problem: error (400) Bad request could be caused by leading '?' in the above code..



     string codeClient = "code="+ t +"&client_id=number.apps.googleusercontent.com&";
    string secretUri = "client_secret=yoursecret&" + "redirect_uri=path&"
    + "grant_type=authorization_code";
    postString = codeClient + secretUri;

    string url = "https://accounts.google.com/o/oauth2/token";

    HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url.ToString());
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";

    UTF8Encoding utfenc = new UTF8Encoding();
    byte[] bytes = utfenc.GetBytes(postString);
    Stream os = null;
    try

    request.ContentLength = bytes.Length;
    os = request.GetRequestStream();
    os.Write(bytes, 0, bytes.Length);

    catch


    try
    {
    HttpWebResponse webResponse = (HttpWebResponse) request.GetResponse();
    Stream responseStream = webResponse.GetResponseStream();
    StreamReader responseStreamReader = new StreamReader(responseStream);
    result = responseStreamReader.ReadToEnd();//parse token from result






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jul 24 '13 at 10:17









    Owen Blacker

    3,2382 gold badges29 silver badges66 bronze badges




    3,2382 gold badges29 silver badges66 bronze badges










    answered Sep 18 '12 at 20:05









    NenoNeno

    3451 gold badge9 silver badges28 bronze badges




    3451 gold badge9 silver badges28 bronze badges















    • what is "t" used for code..and how to get it..

      – user4736499
      Jul 10 '15 at 11:34












    • t the initial authorization code...

      – Martin Pfeffer
      Sep 25 '15 at 19:09











    • It still says Bad Request with this code also

      – Sahil Bhatia
      Jun 27 '17 at 12:20











    • @Sahil, make sure that oauth url is the valid one. Note that I used this code snippet almost 5 years ago.

      – Neno
      Jun 28 '17 at 9:00











    • thanks, it looks like working fine now.

      – Sahil Bhatia
      Jun 28 '17 at 17:07

















    • what is "t" used for code..and how to get it..

      – user4736499
      Jul 10 '15 at 11:34












    • t the initial authorization code...

      – Martin Pfeffer
      Sep 25 '15 at 19:09











    • It still says Bad Request with this code also

      – Sahil Bhatia
      Jun 27 '17 at 12:20











    • @Sahil, make sure that oauth url is the valid one. Note that I used this code snippet almost 5 years ago.

      – Neno
      Jun 28 '17 at 9:00











    • thanks, it looks like working fine now.

      – Sahil Bhatia
      Jun 28 '17 at 17:07
















    what is "t" used for code..and how to get it..

    – user4736499
    Jul 10 '15 at 11:34






    what is "t" used for code..and how to get it..

    – user4736499
    Jul 10 '15 at 11:34














    t the initial authorization code...

    – Martin Pfeffer
    Sep 25 '15 at 19:09





    t the initial authorization code...

    – Martin Pfeffer
    Sep 25 '15 at 19:09













    It still says Bad Request with this code also

    – Sahil Bhatia
    Jun 27 '17 at 12:20





    It still says Bad Request with this code also

    – Sahil Bhatia
    Jun 27 '17 at 12:20













    @Sahil, make sure that oauth url is the valid one. Note that I used this code snippet almost 5 years ago.

    – Neno
    Jun 28 '17 at 9:00





    @Sahil, make sure that oauth url is the valid one. Note that I used this code snippet almost 5 years ago.

    – Neno
    Jun 28 '17 at 9:00













    thanks, it looks like working fine now.

    – Sahil Bhatia
    Jun 28 '17 at 17:07





    thanks, it looks like working fine now.

    – Sahil Bhatia
    Jun 28 '17 at 17:07











    2














    My code is working, I have done mistakes in above two lines. It should be like this



    byte[] buffer = Encoding.ASCII.GetBytes("code=" + code + "&client_id=xxx&client_secret=xxx&redirect_uri=xxxx&grant_type=authorization_code");
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");


    Remaining code is correct.






    share|improve this answer




















    • 2





      What is the Code variable in your code..

      – Devi Prasad
      Jul 10 '15 at 4:00











    • @Viktor: I notice your client id and client secret are both included in the buffer. My hosted website does not have SSL. Do you know if Google will accept my web request from a non SSL connection? Obviously, it would not be safe, and someone could snipe my credentials, but I don't know a way around it.

      – jp2code
      Sep 8 '15 at 22:03















    2














    My code is working, I have done mistakes in above two lines. It should be like this



    byte[] buffer = Encoding.ASCII.GetBytes("code=" + code + "&client_id=xxx&client_secret=xxx&redirect_uri=xxxx&grant_type=authorization_code");
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");


    Remaining code is correct.






    share|improve this answer




















    • 2





      What is the Code variable in your code..

      – Devi Prasad
      Jul 10 '15 at 4:00











    • @Viktor: I notice your client id and client secret are both included in the buffer. My hosted website does not have SSL. Do you know if Google will accept my web request from a non SSL connection? Obviously, it would not be safe, and someone could snipe my credentials, but I don't know a way around it.

      – jp2code
      Sep 8 '15 at 22:03













    2












    2








    2







    My code is working, I have done mistakes in above two lines. It should be like this



    byte[] buffer = Encoding.ASCII.GetBytes("code=" + code + "&client_id=xxx&client_secret=xxx&redirect_uri=xxxx&grant_type=authorization_code");
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");


    Remaining code is correct.






    share|improve this answer













    My code is working, I have done mistakes in above two lines. It should be like this



    byte[] buffer = Encoding.ASCII.GetBytes("code=" + code + "&client_id=xxx&client_secret=xxx&redirect_uri=xxxx&grant_type=authorization_code");
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");


    Remaining code is correct.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Sep 21 '12 at 8:08









    SagarSagar

    1,5794 gold badges16 silver badges29 bronze badges




    1,5794 gold badges16 silver badges29 bronze badges










    • 2





      What is the Code variable in your code..

      – Devi Prasad
      Jul 10 '15 at 4:00











    • @Viktor: I notice your client id and client secret are both included in the buffer. My hosted website does not have SSL. Do you know if Google will accept my web request from a non SSL connection? Obviously, it would not be safe, and someone could snipe my credentials, but I don't know a way around it.

      – jp2code
      Sep 8 '15 at 22:03












    • 2





      What is the Code variable in your code..

      – Devi Prasad
      Jul 10 '15 at 4:00











    • @Viktor: I notice your client id and client secret are both included in the buffer. My hosted website does not have SSL. Do you know if Google will accept my web request from a non SSL connection? Obviously, it would not be safe, and someone could snipe my credentials, but I don't know a way around it.

      – jp2code
      Sep 8 '15 at 22:03







    2




    2





    What is the Code variable in your code..

    – Devi Prasad
    Jul 10 '15 at 4:00





    What is the Code variable in your code..

    – Devi Prasad
    Jul 10 '15 at 4:00













    @Viktor: I notice your client id and client secret are both included in the buffer. My hosted website does not have SSL. Do you know if Google will accept my web request from a non SSL connection? Obviously, it would not be safe, and someone could snipe my credentials, but I don't know a way around it.

    – jp2code
    Sep 8 '15 at 22:03





    @Viktor: I notice your client id and client secret are both included in the buffer. My hosted website does not have SSL. Do you know if Google will accept my web request from a non SSL connection? Obviously, it would not be safe, and someone could snipe my credentials, but I don't know a way around it.

    – jp2code
    Sep 8 '15 at 22:03











    0














    The original request seems to be somewhat outdated. But I found that the Google's code examples contain lots of "Best Practices" housekeeping code that's hard to separate from the essential operations.



    I recently published a document that represents all the REST operations as curl commands. It's hard to be conversant in every language, but curl seems universal. Most people know it- otherwise, it's pretty easy to grasp. In my curl examples, the -d flag indicates a POST operation. Otherwise, the parameters are appended to the URL.



    http://www.tqis.com/eloquency/googlecalendar.htm






    share|improve this answer





























      0














      The original request seems to be somewhat outdated. But I found that the Google's code examples contain lots of "Best Practices" housekeeping code that's hard to separate from the essential operations.



      I recently published a document that represents all the REST operations as curl commands. It's hard to be conversant in every language, but curl seems universal. Most people know it- otherwise, it's pretty easy to grasp. In my curl examples, the -d flag indicates a POST operation. Otherwise, the parameters are appended to the URL.



      http://www.tqis.com/eloquency/googlecalendar.htm






      share|improve this answer



























        0












        0








        0







        The original request seems to be somewhat outdated. But I found that the Google's code examples contain lots of "Best Practices" housekeeping code that's hard to separate from the essential operations.



        I recently published a document that represents all the REST operations as curl commands. It's hard to be conversant in every language, but curl seems universal. Most people know it- otherwise, it's pretty easy to grasp. In my curl examples, the -d flag indicates a POST operation. Otherwise, the parameters are appended to the URL.



        http://www.tqis.com/eloquency/googlecalendar.htm






        share|improve this answer













        The original request seems to be somewhat outdated. But I found that the Google's code examples contain lots of "Best Practices" housekeeping code that's hard to separate from the essential operations.



        I recently published a document that represents all the REST operations as curl commands. It's hard to be conversant in every language, but curl seems universal. Most people know it- otherwise, it's pretty easy to grasp. In my curl examples, the -d flag indicates a POST operation. Otherwise, the parameters are appended to the URL.



        http://www.tqis.com/eloquency/googlecalendar.htm







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 5 '13 at 20:17









        Sunny JimSunny Jim

        3603 silver badges11 bronze badges




        3603 silver badges11 bronze badges
























            0














            public string ReceiveTokenGmail(string code, string GoogleWebAppClientID, string GoogleWebAppClientSecret, string RedirectUrl)

            string postString = "code=" + code + "&client_id=" + GoogleWebAppClientID + @"&client_secret=" + GoogleWebAppClientSecret + "&redirect_uri=" + RedirectUrl;

            string url = "https://accounts.google.com/o/oauth2/token";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            UTF8Encoding utfenc = new UTF8Encoding();
            byte[] bytes = utfenc.GetBytes(postString);
            Stream os = null;
            try

            request.ContentLength = bytes.Length;
            os = request.GetRequestStream();
            os.Write(bytes, 0, bytes.Length);

            catch

            string result = "";

            HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
            Stream responseStream = webResponse.GetResponseStream();
            StreamReader responseStreamReader = new StreamReader(responseStream);
            result = responseStreamReader.ReadToEnd();

            return result;






            share|improve this answer

























            • how do I get the Authentication code from google?. I wanted to use your code so I dont have to use key.json file and just use an app config for my client id and client secret.If you could share how to get the authorization code, that would be awesome.

              – CyberNinja
              Jul 5 '17 at 12:21















            0














            public string ReceiveTokenGmail(string code, string GoogleWebAppClientID, string GoogleWebAppClientSecret, string RedirectUrl)

            string postString = "code=" + code + "&client_id=" + GoogleWebAppClientID + @"&client_secret=" + GoogleWebAppClientSecret + "&redirect_uri=" + RedirectUrl;

            string url = "https://accounts.google.com/o/oauth2/token";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            UTF8Encoding utfenc = new UTF8Encoding();
            byte[] bytes = utfenc.GetBytes(postString);
            Stream os = null;
            try

            request.ContentLength = bytes.Length;
            os = request.GetRequestStream();
            os.Write(bytes, 0, bytes.Length);

            catch

            string result = "";

            HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
            Stream responseStream = webResponse.GetResponseStream();
            StreamReader responseStreamReader = new StreamReader(responseStream);
            result = responseStreamReader.ReadToEnd();

            return result;






            share|improve this answer

























            • how do I get the Authentication code from google?. I wanted to use your code so I dont have to use key.json file and just use an app config for my client id and client secret.If you could share how to get the authorization code, that would be awesome.

              – CyberNinja
              Jul 5 '17 at 12:21













            0












            0








            0







            public string ReceiveTokenGmail(string code, string GoogleWebAppClientID, string GoogleWebAppClientSecret, string RedirectUrl)

            string postString = "code=" + code + "&client_id=" + GoogleWebAppClientID + @"&client_secret=" + GoogleWebAppClientSecret + "&redirect_uri=" + RedirectUrl;

            string url = "https://accounts.google.com/o/oauth2/token";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            UTF8Encoding utfenc = new UTF8Encoding();
            byte[] bytes = utfenc.GetBytes(postString);
            Stream os = null;
            try

            request.ContentLength = bytes.Length;
            os = request.GetRequestStream();
            os.Write(bytes, 0, bytes.Length);

            catch

            string result = "";

            HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
            Stream responseStream = webResponse.GetResponseStream();
            StreamReader responseStreamReader = new StreamReader(responseStream);
            result = responseStreamReader.ReadToEnd();

            return result;






            share|improve this answer













            public string ReceiveTokenGmail(string code, string GoogleWebAppClientID, string GoogleWebAppClientSecret, string RedirectUrl)

            string postString = "code=" + code + "&client_id=" + GoogleWebAppClientID + @"&client_secret=" + GoogleWebAppClientSecret + "&redirect_uri=" + RedirectUrl;

            string url = "https://accounts.google.com/o/oauth2/token";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            UTF8Encoding utfenc = new UTF8Encoding();
            byte[] bytes = utfenc.GetBytes(postString);
            Stream os = null;
            try

            request.ContentLength = bytes.Length;
            os = request.GetRequestStream();
            os.Write(bytes, 0, bytes.Length);

            catch

            string result = "";

            HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
            Stream responseStream = webResponse.GetResponseStream();
            StreamReader responseStreamReader = new StreamReader(responseStream);
            result = responseStreamReader.ReadToEnd();

            return result;







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jul 4 '17 at 18:44









            Sahil BhatiaSahil Bhatia

            1201 silver badge8 bronze badges




            1201 silver badge8 bronze badges















            • how do I get the Authentication code from google?. I wanted to use your code so I dont have to use key.json file and just use an app config for my client id and client secret.If you could share how to get the authorization code, that would be awesome.

              – CyberNinja
              Jul 5 '17 at 12:21

















            • how do I get the Authentication code from google?. I wanted to use your code so I dont have to use key.json file and just use an app config for my client id and client secret.If you could share how to get the authorization code, that would be awesome.

              – CyberNinja
              Jul 5 '17 at 12:21
















            how do I get the Authentication code from google?. I wanted to use your code so I dont have to use key.json file and just use an app config for my client id and client secret.If you could share how to get the authorization code, that would be awesome.

            – CyberNinja
            Jul 5 '17 at 12:21





            how do I get the Authentication code from google?. I wanted to use your code so I dont have to use key.json file and just use an app config for my client id and client secret.If you could share how to get the authorization code, that would be awesome.

            – CyberNinja
            Jul 5 '17 at 12:21

















            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%2f11833281%2fhow-to-get-access-token-for-google-oauth%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