OneDrive / onedrive-sdk-dotnet-msa-auth-adapter

Other
26 stars 22 forks source link

"A task was canceled." error from RedeemAuthorizationCodeAsync from WebApp #6

Closed shrimpy closed 7 years ago

shrimpy commented 8 years ago

With below code, "A task was canceled." was throw when try to authorize token.

        [HttpGet]
        [Route("api/Auth/OneDriveAuth")]
        public RedirectResult AuthOneDrive()
        {
            OAuthHelper helper = new OAuthHelper();
            return this.Redirect(helper.GetAuthorizationCodeRequestUrl(OneDriveClientId, OneDriveRedirectUrl, new string[] { "offline_access", "onedrive.readonly" }));
        }

        [HttpGet]
        [Route("api/Auth/OneDriveCallback")]
        public async Task<object> AuthOneDriveCallback(string code)
        {
            try
            {
                MyOAuthHelper helper = new MyOAuthHelper();
                AccountSession account = await helper.RedeemAuthorizationCodeAsync(code, OneDriveClientId, OneDriveSecret, OneDriveRedirectUrl, new string[] { "offline_access", "onedrive.readonly" });
                return account;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

Updated to below code, i am able to get correct token

              string body = helper.GetAuthorizationCodeRedemptionRequestBody(code, OneDriveClientId, OneDriveRedirectUrl, new string[] { "offline_access", "onedrive.readonly" }, OneDriveSecret);
                var content = new StringContent(body);
                content.Headers.ContentType = new MediaTypeHeaderValue(Constants.FormUrlEncodedMediaType);
                using (var client = CreateHttpClient())
                using (var response = await client.PostAsync("https://login.live.com/oauth20_token.srf", content))
                {
                    return await response.Content.ReadAsStringAsync();
                }
chrispatrick commented 8 years ago

I just ran into this same issue. I believe it comes from using the overload of RedeemAuthorizationCodeAsync that doesn't take an HttpProvider.

It looks like the HttpProvider gets disposed before the task has been awaited, which cancels the request.

Easy workaround is to surround the call to RedeemAuthorizationCodeAsync with using(var httpProvider = new HttpProvider()) and pass that HttpProvider in.

cdmayer commented 8 years ago

This is a bug. Thanks for reporting. Going to send out the fix in the next update, which should be coming soon.

Meanwhile, use @chrispatrick 's workaround.

cdmayer commented 8 years ago

@shrimpy I believe this is fixed in 1.0.3. Can you update your NuGet package and give it a shot?

cdmayer commented 7 years ago

Fixed