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.

6
  • 1
    Why don't you use code.google.com/p/google-api-dotnet-client/wiki/OAuth2 Commented Aug 6, 2012 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. Commented Aug 6, 2012 at 19:39
  • What is "code" in ur buffer?? Commented Oct 11, 2012 at 6:17
  • @Apoorva It is a authorisation code. Commented Oct 11, 2012 at 16:55
  • How to get authorisation code...can you please tell me i don't know about it.. Commented Jul 10, 2015 at 11:33

6 Answers 6

10

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

Sign up to request clarification or add additional context in comments.

2 Comments

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?
Drill down into the details of the exception, the complete error message will tell you what is wrong with your request
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

4 Comments

@Sahil, make sure that oauth url is the valid one. Note that I used this code snippet almost 5 years ago.
@CyberNinja see my code in this same forum. It works perfect. Let me know for any other issue.
@SahilBhatia what I mean is how do you get the code that you pass as your param, like how do you request that from google thru .net code? I know you can request that via url as a request_type in the browser but it will ask me to login in.
I tried in similar way but getting the bad response, can someone help ?.
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.

3 Comments

@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.
I stopped reading at "does not have SSL". Use SSL.
@sager, what is this code variable?
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

Comments

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;
}

1 Comment

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.
0

It was surprisingly difficult to find the correct and simple way of getting access token by auth code. (Especially because it has taken some time for me and then even with the correct code I got “invalid_grant” error because my auth code expired while searching :) )

So here is the code:

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(
  new GoogleAuthorizationCodeFlow.Initializer
  {
    ClientSecrets = new ClientSecrets()
    {
      // Use ones from "Web SDK configuration" section if you created your app in Firebase.
      ClientId = "…",
      ClientSecret = "…"
    },
    Scopes = new[] { "email" },
  }
);

TokenResponse token = await  flow.ExchangeCodeForTokenAsync(string.Empty, "4/…", string.Empty, CancellationToken.None);

As you can see, userId can be just empty, as well as redirectUri. Don’t forget to add the Google.Apis.Auth Nuget package reference.

1 Comment

How did you get the code "4/…" in your example?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.