コード例 #1
0
        /// <summary>
        ///     Check and authenticate or refresh tokens
        /// </summary>
        /// <param name="cancellationToken">CancellationToken</param>
        private async Task CheckAndAuthenticateOrRefreshAsync(CancellationToken cancellationToken = default)
        {
            _httpBehaviour.MakeCurrent();

            Log.Debug().WriteLine("Checking authentication.");
            // Get Refresh / Access token
            if (string.IsNullOrEmpty(_oAuth2Settings.Token.OAuth2AccessToken))
            {
                Log.Debug().WriteLine("No token, performing an Authentication");
                if (!await AuthenticateAsync(cancellationToken).ConfigureAwait(false))
                {
                    throw new Exception("Authentication cancelled");
                }
            }
            if (_oAuth2Settings.IsAccessTokenExpired)
            {
                Log.Debug().WriteLine("Access-token expired, refreshing token");
                await GenerateAccessTokenAsync(cancellationToken).ConfigureAwait(false);

                // Get Refresh / Access token
                if (string.IsNullOrEmpty(_oAuth2Settings.Token.OAuth2RefreshToken))
                {
                    if (!await AuthenticateAsync(cancellationToken).ConfigureAwait(false))
                    {
                        throw new Exception("Authentication cancelled");
                    }
                    await GenerateAccessTokenAsync(cancellationToken).ConfigureAwait(false);
                }
            }
            if (_oAuth2Settings.IsAccessTokenExpired)
            {
                throw new Exception("Authentication failed");
            }
        }
コード例 #2
0
        /// <summary>
        ///     Retrieve the thumbnail of an imgur image
        /// </summary>
        /// <param name="token"></param>
        public async Task <int> RetrieveImgurCredits(CancellationToken token = default)
        {
            var creditsUri = ApiUri.AppendSegments("3", "credits.json");

            _oAuthHttpBehaviour.MakeCurrent();
            using (var client = HttpClientFactory.Create(creditsUri))
            {
                var response = await client.GetAsync(creditsUri, token).ConfigureAwait(false);

                await response.HandleErrorAsync().ConfigureAwait(false);

                var creditsJson = await response.GetAsAsync <dynamic>(token).ConfigureAwait(false);

                if ((creditsJson != null) && creditsJson.ContainsKey("data"))
                {
                    dynamic data = creditsJson.data;
                    if (data.ContainsKey("ClientRemaining"))
                    {
                        Log.Debug().WriteLine("{0}={1}", "ClientRemaining", (int)data.ClientRemaining);
                        return((int)data.ClientRemaining);
                    }
                    if (data.ContainsKey("UserRemaining"))
                    {
                        Log.Debug().WriteLine("{0}={1}", "UserRemaining", (int)data.UserRemaining);
                        return((int)data.UserRemaining);
                    }
                }

                return(-1);
            }
        }
コード例 #3
0
        public async Task TestOAuthHttpMessageHandler_Get()
        {
            var userInformationUri = OAuthTestServerUri.AppendSegments("echo_api.php").ExtendQuery("name", "dapplo");

            // Make sure you use your special IHttpBehaviour for the OAuth requests!
            _oAuthHttpBehaviour.MakeCurrent();
            var response = await userInformationUri.GetAsAsync <string>();

            Assert.Contains("dapplo", response);
        }
コード例 #4
0
        /// <summary>
        ///     This will test Oauth with a LocalServer "code" receiver against a demo oauth server provided by brentertainment.com
        /// </summary>
        /// <returns>Task</returns>
        //[Fact]
        public async Task TestOAuth2HttpMessageHandler()
        {
            var calendarApiUri = GoogleApiUri.AppendSegments("calendar", "v3");

            // Make sure you use your special IHttpBehaviour before the requests which need OAuth
            _oAuthHttpBehaviour.MakeCurrent();
            var response = await calendarApiUri.AppendSegments("users", "me", "calendarList").GetAsAsync <dynamic>();

            Assert.True(response.ContainsKey("items"));
            Assert.True(response["items"].Count > 0);
        }
コード例 #5
0
        /// <summary>
        ///     Upload the HttpContent to dropbox
        /// </summary>
        /// <param name="filename">Name of the file</param>
        /// <param name="content">HttpContent</param>
        /// <param name="progress">IProgress</param>
        /// <param name="cancellationToken">CancellationToken</param>
        /// <returns>Url as string</returns>
        private async Task <string> UploadAsync(string filename, HttpContent content, IProgress <int> progress = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            var oAuthHttpBehaviour = _oAuthHttpBehaviour.ShallowClone();

            // Use UploadProgress
            if (progress != null)
            {
                oAuthHttpBehaviour.UploadProgress = percent => { UiContext.RunOn(() => progress.Report((int)(percent * 100))); };
            }
            oAuthHttpBehaviour.MakeCurrent();

            // Build the upload content together
            var uploadContent = new Upload
            {
                Content = content
            };

            // This is needed
            if (!filename.StartsWith("/"))
            {
                filename = "/" + filename;
            }
            // Create the upload request parameters
            var parameters = new UploadRequest
            {
                Path = filename
            };

            // Add it to the headers
            uploadContent.Headers.Add("Dropbox-API-Arg", JsonConvert.SerializeObject(parameters, Formatting.None));
            _oAuthHttpBehaviour.MakeCurrent();
            // Post everything, and return the upload reply or an error
            var response = await DropboxContentUri.PostAsync <HttpResponse <UploadReply, Error> >(uploadContent, cancellationToken).ConfigureAwait(false);

            if (response.HasError)
            {
                throw new ApplicationException(response.ErrorResponse.Summary);
            }
            // Take the response from the upload, and use the information to request dropbox to create a link
            var createLinkRequest = new CreateLinkRequest
            {
                Path = response.Response.PathDisplay
            };
            var reply = await DropboxApiUri
                        .AppendSegments("2", "sharing", "create_shared_link_with_settings")
                        .PostAsync <HttpResponse <CreateLinkReply, Error> >(createLinkRequest, cancellationToken).ConfigureAwait(false);

            if (reply.HasError)
            {
                throw new ApplicationException(reply.ErrorResponse.Summary);
            }
            return(reply.Response.Url);
        }
コード例 #6
0
ファイル: JiraApi.cs プロジェクト: Miranous/Dapplo.Jira
        /// <summary>
        /// Returns the content, specified by the Urim from the JIRA server.
        /// This is used internally, but can also be used to get e.g. the icon for an issue type.
        /// </summary>
        /// <typeparam name="TResponse"></typeparam>
        /// <param name="contentUri">Uri</param>
        /// <param name="cancellationToken">CancellationToken</param>
        /// <returns>TResponse</returns>
        public async Task <TResponse> GetUriContentAsync <TResponse>(Uri contentUri, CancellationToken cancellationToken = default(CancellationToken))
            where TResponse : class
        {
            Log.Debug().WriteLine("Retrieving content from {0}", contentUri);

            _behaviour.MakeCurrent();

            var response = await contentUri.GetAsAsync <HttpResponse <TResponse, string> >(cancellationToken).ConfigureAwait(false);

            if (response.HasError)
            {
                throw new Exception($"Status: {response.StatusCode} Message: {response.ErrorResponse}");
            }
            return(response.Response);
        }