【问题标题】:Box API always returns invalid grant_type parameter on obtaining access tokenBox API 在获取访问令牌时总是返回无效的 grant_type 参数
【发布时间】:2014-08-31 17:47:26
【问题描述】:

我正在为 WP8 编写自己的 Box SDK,以充分利用 Tasks。我在获取访问令牌时遇到问题。我总是得到这个作为回报:

{"error":"invalid_request","error_description":"Invalid grant_type parameter or parameter missing"}

我正在使用的代码(全部在 C# 中)是:

    internal const String TokenURL = "https://api.box.com/oauth2/token";

CloudHttpAsync.DownloadResponceStreamAsync
(
    CloudHttpAsync.PostAsync
    (
        TokenURL,
        new MemoryStream
        (
            UTF8Encoding.UTF8.GetBytes
            (
                HttpUtility.UrlEncode
                (
                    String.Format
                    (
                        "grant_type=authorization_code&code={0}&client_id={1}&client_secret={2}&redirect_uri={3}",
                        Code,
                        ClientID,
                        ClientSecret,
                        RedirectURI
                    )
                )
            )
        ),
        null,
        null
    ),
    null
).ContinueWith((AsyncStream) =>
    {
        try
        {
            if (AsyncStream.Exception != null)
            {
                TaskSource.TrySetException(AsyncStream.Exception.InnerExceptions);
                return;
            }

            String Result = "";
            using (StreamReader Reader = new StreamReader(AsyncStream.Result))
            {
                Result = Reader.ReadToEnd();
            }

            BoxAuthToken Token = JsonConvert.DeserializeObject<BoxAuthToken>(Result);
            TaskSource.TrySetResult(Token);
        }
        catch (Exception e)
        {
            TaskSource.TrySetException(e);
        }
    });

    public static Task<HttpWebResponse> PostAsync(String URL, Stream UploadData, IRequestSigner Signer, IProgress<NetworkProgress> Progress)
    {
        TaskCompletionSource<HttpWebResponse> TaskSource = new TaskCompletionSource<HttpWebResponse>();

        HttpWebRequest Request = WebRequest.CreateHttp(URL);
        Request.Method = "POST";

        if (Signer != null)
        {
            Signer.Sign(Request).ContinueWith((o) =>
            {
                if (o.Exception != null)
                {
                    TaskSource.TrySetException(o.Exception.InnerExceptions);
                    return;
                }

                UploadDataAsync(Request, UploadData, Progress).ContinueWith((AsyncRequest) =>
                {
                    if (AsyncRequest.Exception != null)
                    {
                        TaskSource.TrySetException(AsyncRequest.Exception.InnerExceptions);
                        return;
                    }

                    GetResponceAsync(Request).ContinueWith((AsyncResponce) =>
                    {
                        if (AsyncResponce.Exception != null)
                        {
                            TaskSource.TrySetException(AsyncResponce.Exception.InnerExceptions);
                            return;
                        }

                        TaskSource.TrySetResult(AsyncResponce.Result);
                    });
                });
            });
        }
        else
        {
            UploadDataAsync(Request, UploadData, Progress).ContinueWith((AsyncRequest) =>
            {
                if (AsyncRequest.Exception != null)
                {
                    TaskSource.TrySetException(AsyncRequest.Exception.InnerExceptions);
                    return;
                }

                GetResponceAsync(Request).ContinueWith((AsyncResponce) =>
                {
                    if (AsyncResponce.Exception != null)
                    {
                        TaskSource.TrySetException(AsyncResponce.Exception.InnerExceptions);
                        return;
                    }

                    TaskSource.TrySetResult(AsyncResponce.Result);
                });
            });
        }

        return TaskSource.Task;
    }

    internal static Task<HttpWebRequest> UploadDataAsync(HttpWebRequest Request, Stream Data, IProgress<NetworkProgress> Progress)
    {
        TaskCompletionSource<HttpWebRequest> TaskSource = new TaskCompletionSource<HttpWebRequest>();

        if (Data.Length != 0)
        {
            Request.ContentLength = Data.Length;
            Request.AllowWriteStreamBuffering = false;

            Request.BeginGetRequestStream(new AsyncCallback((IAR) =>
                {
                    try
                    {
                        using (Stream UploadStream = Request.EndGetRequestStream(IAR))
                        {
                            Int64 Upload = 0;
                            Int64 TotalUploaded = 0;
                            Int64 Total = Data.Length;
                            Byte[] Buffer = new Byte[4096];

                            while (TotalUploaded < Total)
                            {
                                Upload = Data.Read(Buffer, 0, Buffer.Length);
                                TotalUploaded += Upload;
                                UploadStream.Write(Buffer, 0, (Int32)Upload);

                                if (Progress != null)
                                {
                                    Progress.Report(new NetworkProgress()
                                    {
                                        Operation = NetworkOperation.Uploading,
                                        TotalBytes = Total,
                                        BytesProcessed = TotalUploaded
                                    });
                                }
                            }
                        }

                        TaskSource.TrySetResult(Request);
                    }
                    catch (Exception e)
                    {
                        TaskSource.TrySetException(e);
                    }
                }),
                null);
        }
        else
        {
            TaskSource.TrySetResult(Request);
        }

        return TaskSource.Task;
    }

    internal static Task<HttpWebResponse> GetResponceAsync(HttpWebRequest Request)
    {
        TaskCompletionSource<HttpWebResponse> TaskSource = new TaskCompletionSource<HttpWebResponse>();

        Request.BeginGetResponse(new AsyncCallback((IAR) =>
            {
                try
                {
                    HttpWebResponse Responce = (HttpWebResponse)Request.EndGetResponse(IAR);
                    TaskSource.TrySetResult(Responce);
                }
                catch (Exception e)
                {
                    if (e is WebException && (e as WebException).Response.ContentLength > 0)
                    {
                        TaskSource.TrySetResult((HttpWebResponse)(e as WebException).Response);
                    }
                    else
                    {
                        TaskSource.TrySetException(e);
                    }
                }
            }),
            null);

        return TaskSource.Task;
    }

    public static Task<StreamAndLength> GetResponceStreamAsync(Task<HttpWebResponse> Task)
    {
        TaskCompletionSource<StreamAndLength> TaskSource = new TaskCompletionSource<StreamAndLength>();

        Task.ContinueWith((AsyncHWR) =>
            {
                if (AsyncHWR.Exception != null)
                {
                    TaskSource.TrySetException(AsyncHWR.Exception.InnerExceptions);
                    return;
                }

                HttpWebResponse Responce = AsyncHWR.Result;
                TaskSource.TrySetResult( new StreamAndLength() { Stream = Responce.GetResponseStream(), Length = Responce.ContentLength });
            });

        return TaskSource.Task;
    }

    public static Task<MemoryStream> DownloadResponceStreamAsync(Task<HttpWebResponse> Task, IProgress<NetworkProgress> Progress)
    {
        TaskCompletionSource<MemoryStream> TaskSource = new TaskCompletionSource<MemoryStream>();

        GetResponceStreamAsync(Task).ContinueWith((AsyncStream) =>
            {
                if (AsyncStream.Exception != null)
                {
                    TaskSource.TrySetException(AsyncStream.Exception.InnerExceptions);
                    return;
                }

                MemoryStream MemStream = new MemoryStream();
                MemStream.SetLength(AsyncStream.Result.Length);

                Int64 CurrentRead = 0;
                Int64 TotalRead = 0;
                Int64 Total = AsyncStream.Result.Length;
                Byte[] Buffer = new Byte[4096];

                using (Stream DownloadStream = AsyncStream.Result.Stream)
                while (TotalRead < Total)
                {
                    CurrentRead = DownloadStream.Read(Buffer, 0, Buffer.Length);
                    MemStream.Write(Buffer, 0, (Int32)CurrentRead);
                    TotalRead += CurrentRead;

                    if (Progress != null)
                    {
                        Progress.Report(new NetworkProgress()
                        {
                            Operation = NetworkOperation.Downloading,
                            TotalBytes = Total,
                            BytesProcessed = TotalRead
                        });
                    }
                }

                MemStream.Position = 0;
                TaskSource.TrySetResult(MemStream);
            });

        return TaskSource.Task;
    }

    internal class StreamAndLength
    {
        public Stream Stream { get; set; }
        public Int64 Length { get; set; }
    }

对不起,代码很多,我喜欢写通用的:)

编辑:原始响应(删除了 ClientID 和 Client Secret)

当对每个值进行 URL 编码时:

POST https://api.box.com/oauth2/token HTTP/1.1
Accept: */*
Content-Length: 196
Accept-Encoding: identity
User-Agent: NativeHost
Host: api.box.com
Connection: Keep-Alive
Cache-Control: no-cache

grant_type=authorization_code&code=JknaLbfT6lAXmey3FLYrp9eg1jMbpFuQ&client_id=[subbed]&client_secret=[subbed]&redirect_uri=https%3a%2f%2fCloudBoxWP8

返回:

HTTP/1.1 400 Bad Request
Server: nginx
Date: Fri, 01 Mar 2013 07:35:22 GMT
Content-Type: application/json
Connection: keep-alive
Set-Cookie: box_visitor_id=51305a3a187f34.52738262; expires=Sat, 01-Mar-2014 07:35:22 GMT; path=/; domain=.box.com
Set-Cookie: country_code=US; expires=Tue, 30-Apr-2013 07:35:22 GMT; path=/
Cache-Control: no-store
Content-Length: 99

{"error":"invalid_request","error_description":"Invalid grant_type parameter or parameter missing"}

当 URL 编码整个字符串时:

POST https://api.box.com/oauth2/token HTTP/1.1
Accept: */*
Content-Length: 214
Accept-Encoding: identity
User-Agent: NativeHost
Host: api.box.com
Connection: Keep-Alive
Cache-Control: no-cache

grant_type%3dauthorization_code%26code%3d3ikruv5elfdw3fOP55aMDSX7ybLqBFlA%26client_id%3d[subbed]%26client_secret%3d[subbed]%26redirect_uri%3dhttps%3a%2f%2fCloudBoxWP8

返回

HTTP/1.1 400 Bad Request
Server: nginx
Date: Fri, 01 Mar 2013 07:46:03 GMT
Content-Type: application/json
Connection: keep-alive
Set-Cookie: box_visitor_id=51305cbb339de4.03221876; expires=Sat, 01-Mar-2014 07:46:03 GMT; path=/; domain=.box.com
Set-Cookie: country_code=US; expires=Tue, 30-Apr-2013 07:46:03 GMT; path=/
Cache-Control: no-store
Content-Length: 99

{"error":"invalid_request","error_description":"Invalid grant_type parameter or parameter missing"}

无 URL 编码:

POST https://api.box.com/oauth2/token HTTP/1.1
Accept: */*
Content-Length: 190
Accept-Encoding: identity
User-Agent: NativeHost
Host: api.box.com
Connection: Keep-Alive
Cache-Control: no-cache

grant_type=authorization_code&code=2wgIzfqhvIgRtVIp2ZvqZ9X8R5u0QNaf&client_id=[subbed]&client_secret=[subbed]&redirect_uri=https://CloudBoxWP8

返回:

HTTP/1.1 400 Bad Request
Server: nginx
Date: Fri, 01 Mar 2013 07:50:31 GMT
Content-Type: application/json
Connection: keep-alive
Set-Cookie: box_visitor_id=51305dc751d7f5.67064854; expires=Sat, 01-Mar-2014 07:50:31 GMT; path=/; domain=.box.com
Set-Cookie: country_code=US; expires=Tue, 30-Apr-2013 07:50:31 GMT; path=/
Cache-Control: no-store
Content-Length: 99

{"error":"invalid_request","error_description":"Invalid grant_type parameter or parameter missing"}

【问题讨论】:

  • Tom,你能发布一个 Fiddler 跟踪发送到 Box 的 HTTP 请求吗?
  • 另外,您是否对重定向 uri 进行了 URL 编码?
  • 刚刚尝试了仅将重定向地址编码为相同结果的 URL。现在使用提琴手我已经尝试使用它来发送 POST,使用应该是有效的请求正文它也返回 no grant_type 错误。再次尝试,我使用请求正文“grant_type=authorization_code”向api.box.com/oauth2/token 发出 POST 请求,但我仍然收到 no grant_type 错误!
  • 您能否发布原始请求和响应数据(已删除任何秘密信息)?
  • 完成,希望对您有所帮助

标签: box-api


【解决方案1】:

它没有在 Box API 文档的任何地方列出,但检索访问令牌的请求需要标头 Content-Type: application/x-www-form-urlencoded

我也被这部分卡住了一段时间,直到我在 StackOverflow 上找到了答案。不过我忘记了它的链接。

【讨论】:

    【解决方案2】:

    请求/响应会有所帮助。看起来您正在对整个查询字符串进行 UrlEncoding,而不仅仅是对每个值进行编码。这将提交给我们: grant_type%3Dauthorization_code%26code%3Dxyz%26client_id%3Dxyz%26client_secret%3Dxyz%26redirect_uri%3Dxyz

    而不是: grant_type=authorization_code&code=xyz&client_id=xyz&client_secret=xyz&redirect_uri=xyz

    【讨论】:

    • 刚刚尝试过没有效果。我已经发布了原始请求和响应数据,以便您查看自己
    【解决方案3】:

    我认为在您的请求正文中包含 redirect_uri 可能会使事情变得复杂,特别是因为它看起来被设置为无效值 (https://CloudBoxWP8) 您可以通过将您的应用设置为处理自定义协议 ( cloudboxwp8://) 并预先配置 Box 以在授予令牌时重定向到该位置。

    1. Register a custom protocol 用于您的 WP8 应用程序。例如,cloudboxwp8
    2. 增强您的 WP8 应用程序以处理对该协议上某些端点的请求。例如,cloudboxwp8://tokengranted。在此处实现您的令牌处理逻辑。
    3. 编辑您的 Box 应用程序并浏览到 OAuth2 参数部分(通过 Manage a Box Application => 编辑应用程序)
    4. redirect_uri 字段中,将值设置为步骤 2 中的自定义协议和端点。保存更改。
    5. 从您的请求正文中删除 redirect_uri,然后重试您的请求。

    【讨论】:

    • 我这几天有点忙,会一直忙到周末。那我试试这个。需要指出的是,我可以通过在应用程序中弹出的 WebBrowser 控件很好地执行登录部分(因此我正在编写的库是完全自包含的),这种方法与其他 OAuth 实现(例如 Dropbox)一起工作得很好。抱歉回复晚了!
    【解决方案4】:

    在 Windows phone 8.1 WinRT 中

    Dictionary<string, string> contentList = new Dictionary<string, string>();
    
    contentList.Add("code", code);
    contentList.Add("client_id", client_id);
    contentList.Add("client_secret", clientSecret);
    contentList.Add("redirect_uri", redirectUri);
    contentList.Add("grant_type", "authorization_code");
    
    FormUrlEncodedContent content = new FormUrlEncodedContent(contentList);
    
    var response = await client.PostAsync(baseURL, content);
    YouTubeAutenticationResponse res =       JsonConvert.DeserializeObject<YouTubeAutenticationResponse>(await     response.Content.ReadAsStringAsync());
    
    public class YouTubeAutenticationResponse
    {
        [JsonProperty("access_token")]
        public string AccessToken { get; set; }
        [JsonProperty("token_type")]
        public string TokenType { get; set; }
        [JsonProperty("expires_in")]
        public string ExpiresIn { get; set; }
        [JsonProperty("refresh_token")]
        public string RefreshToken { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-06
      • 2018-07-23
      • 1970-01-01
      • 2012-04-15
      • 1970-01-01
      • 2013-08-19
      • 2016-07-07
      • 2013-01-09
      相关资源
      最近更新 更多