如何为谷歌oauth获取访问令牌?

时间:2022-05-26 15:14:44

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 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 (is I going in a right way). I use this code....

我使用的是c# (ASP.NET)。我想使用谷歌oauth来访问我的应用程序中的用户概要文件。我成功获得了授权代码,但在获取访问令牌时遇到了问题。我更喜欢谷歌教程。在教程中,我读到我必须发送请求并从谷歌得到响应。我使用System.Net。HttpWebRequest/HttpWebResponse(我用的是正确的方式)。我用这段代码....

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.

远程服务器返回错误:(405)方法不允许。

Update: Here variable code is authorization code.

更新:这里的变量代码是授权代码。

5 个解决方案

#1


8  

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

我认为您将POST请求发送到错误的端点,正确的是https://accounts.google.com/o/oauth2/token。

#2


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

由于我在实现谷歌auth的过程中遇到了类似的问题,我将发布工作的代码。最后提到的问题:错误(400)错误请求可能是由领导造成的?“在上面的代码中……”

 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

#3


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.

剩下的代码是正确的。

#4


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.

我最近发布了一个文档,它代表curl命令的所有REST操作。在每种语言中都很难精通,但curl似乎是通用的。大多数人都知道——否则,很容易掌握。在我的curl示例中,-d标志表示一个POST操作。否则,参数将附加到URL。

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

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

#5


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


8  

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

我认为您将POST请求发送到错误的端点,正确的是https://accounts.google.com/o/oauth2/token。

#2


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

由于我在实现谷歌auth的过程中遇到了类似的问题,我将发布工作的代码。最后提到的问题:错误(400)错误请求可能是由领导造成的?“在上面的代码中……”

 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

#3


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.

剩下的代码是正确的。

#4


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.

我最近发布了一个文档,它代表curl命令的所有REST操作。在每种语言中都很难精通,但curl似乎是通用的。大多数人都知道——否则,很容易掌握。在我的curl示例中,-d标志表示一个POST操作。否则,参数将附加到URL。

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

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

#5


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