【问题标题】:Bad Request trying to retrieve Tokens from Google with C#尝试使用 C# 从 Google 检索令牌的错误请求
【发布时间】:2014-01-12 19:53:54
【问题描述】:

我正在尝试复制此处详述的过程; https://developers.google.com/accounts/docs/OAuth2WebServer#handlingtheresponse

在 C# 中

        String authorizationCode = String.Empty;
        String consumerKey       = String.Empty;
        String consumerSecret    = String.Empty;
        String redirectUrl       = String.Empty;
        String grantType         = String.Empty;
        String requestContent = String.Empty;
        HttpWebRequest request = null;
        byte[] byteArray = null;
        Stream dataStream = null;
        WebResponse response = null;
        StreamReader reader = null;
        String serverResponse = String.Empty;

        byte[] authorizationResult = null;

        try
        {
            authorizationCode = HttpUtility.UrlEncode(context.Request.QueryString["code"]);
            consumerKey       = Properties.Settings.Default.GoogleConsumerKey;
            consumerSecret    = Properties.Settings.Default.GoogleConsumerSecret;
            redirectUrl       = Properties.Settings.Default.RedirectUrl;
            grantType = "authorization_code";

            request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
            request.Method = "POST";

            requestContent = String.Format("code={0}&client_id={1}&client_secret={2}&redirect_url={3}&grant_type={4}",authorizationCode,consumerKey,consumerSecret,redirectUrl,grantType);
            byteArray = Encoding.UTF8.GetBytes(requestContent);

            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;

            dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            response = request.GetResponse();
            dataStream = response.GetResponseStream();

            reader = new StreamReader(dataStream);
            serverResponse = HttpUtility.UrlDecode(reader.ReadToEnd());

            reader.Close();
            dataStream.Close();
            response.Close();



        }
        catch (System.Exception ex)
        {
            throw ex;
        }
        finally
        {

        }

问题是在调用 GetResponse() 时收到错误请求。

ConsumerKey & Secret 是我在注册应用程序时从 Google 获得的。授权码也来自谷歌。

任何想法我做错了什么?

提前致谢。

【问题讨论】:

  • 您可以使用 Fiddler 之类的工具来捕获它实际发送的原始请求并将其粘贴到此处吗?
  • 还有 Paul,您第二次得到的确切错误消息是什么,调试代码时的哪一行是抛出的错误..?

标签: c# oauth


【解决方案1】:

我有同样的问题: “使用”关键字为我解决了这个问题。点击链接:

https://stackoverflow.com/a/1968543/1820776

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 2021-11-04
    • 2019-06-23
    • 2013-07-21
    • 2023-03-05
    • 2021-08-06
    • 2012-04-22
    相关资源
    最近更新 更多