asp.net 如何获得谷歌oauth的访问令牌?

k5ifujac  于 2022-11-19  发布在  .NET
关注(0)|答案(6)|浏览(212)

我使用的是C#(ASP.NET)。我想使用GoogleOAuth访问我的应用程序中的用户配置文件详细信息。我成功地获得了授权码,但在获得访问令牌时遇到了问题。我更喜欢Google tutorials。在教程中,我读到我必须发送请求并从Google获得响应。为此,我使用了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);

但是,我得到了错误:
远程服务器返回错误:(405)不允许的方法。
更新:此处变量code是授权代码。

j91ykkif

j91ykkif1#

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

gz5pxeao

gz5pxeao2#

由于我在实现Google 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
nnsrf1az

nnsrf1az3#

我的代码是工作的,我做了以上两行的错误。它应该是这样的

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");

剩余代码正确。

daolsyd0

daolsyd04#

最初的要求似乎有点过时了,但我发现Google的代码示例包含了很多“最佳实践”的内务代码,很难将它们与基本操作分开。
我最近发布了一个文档,将所有REST操作表示为curl命令。要精通每一种语言是很困难的,但curl似乎是通用的。大多数人都知道它--否则,它很容易掌握。在我的curl示例中,-d 标志表示POST操作。否则,参数将附加到URL。
http://www.tqis.com/eloquency/googlecalendar.htm

mzmfm0qo

mzmfm0qo5#

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

qc6wkl3g6#

这是令人惊讶的困难,找到正确和简单的方式获得访问令牌的授权码.(特别是因为它已经花了一些时间,我,然后即使与正确的代码,我得到了“invalid_grant”错误,因为我的授权码过期,而搜索:))
代码如下:

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

正如您所看到的,userIdredirectUri一样可以是空的。不要忘记添加Google.Apis.AuthNuget包引用。

相关问题