盒API总是返回上获得访问令牌无效grant_type参数(Box API always retur

2019-07-20 15:46发布

我在写我自己的盒子SDK为WP8做出最出任务。 我无法获得访问令牌。 我总是得到这样的回报:

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

对不起有大量的代码,我喜欢一般写:)

编辑:原Responces(客户端ID和客户端密钥删除)

当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"}

Answer 1:

这不是盒API文档上的任何地方上市,但是对于检索访问令牌的请求需要头Content-Type: application/x-www-form-urlencoded

我还停留在这一部分一段时间,直到我发现StackOverflow的答案。 我忘了链接到它虽然。



Answer 2:

请求/响应将是有益的。 它看起来像你的URL编码整个查询字符串,而不是仅仅每个值。 这将提交给我们:grant_type%3Dauthorization_code%26code%3Dxyz%26client_id%3Dxyz%26client_secret%3Dxyz%26redirect_uri%3Dxyz

代替:grant_type = authorization_code&代码= XYZ&CLIENT_ID = XYZ&client_secret = XYZ&REDIRECT_URI = XYZ



Answer 3:

我认为,包括redirect_uri在你的请求主体可能是复杂的东西,特别是因为它看起来被设置为无效值( https://CloudBoxWP8 )你可以通过设置你的应用程序来处理自定义协议(解决此cloudboxwp8:// )和预先配置盒当令牌被授予重定向到。

  1. 注册自定义协议为您的WP8应用程序。 例如, cloudboxwp8
  2. 增加自己的WP8应用程序以处理对协议的一些端点的请求。 例如, cloudboxwp8://tokengranted 。 在这里实现你的令牌处理逻辑。
  3. 编辑您的盒子的应用程序和浏览到的OAuth2 paramters部分(通过管理箱应用程序 =>编辑应用程序)
  4. redirect_uri场,将该值设置为从步骤2中保存更改自定义的协议和端点。
  5. 取出redirect_uri从您的请求主体,并再次尝试您的请求。


Answer 4:

在Windows手机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; }
}


文章来源: Box API always returns invalid grant_type parameter on obtaining access token
标签: box-api