示例#1
0
 public Task RevokeTokenAsync(OAuth2Token token)
 {
     throw new NotImplementedException();
 }
示例#2
0
        private void PluginForm_Shown(object sender, EventArgs e)
        {
            _oAuth2Token = GetSavedToken();
            var api = new DropboxApi(SeAppKey, SeAppsecret, _oAuth2Token);

            if (_oAuth2Token == null)
            {
                try
                {
                    Process.Start(api.GetPromptForCodeUrl());
                    using (var form = new GetDropBoxCode())
                    {
                        var result = form.ShowDialog(this);
                        if (result == DialogResult.OK && form.Code.Length > 10)
                        {
                            _oAuth2Token = api.GetAccessToken(form.Code);
                        }
                        else
                        {
                            MessageBox.Show("Code skipped - no Dropbox :(");
                            return;
                        }
                    }
                    labelInfo.Text = string.Empty;
                    SaveToken(_oAuth2Token);
                }
                catch (Exception exception)
                {
                    _connectTries++;
                    if (_connectTries < 2)
                    {
                        PluginForm_Shown(sender, e);
                        return;
                    }
                    MessageBox.Show(exception.Message);
                    buttonOK.Enabled = false;
                    return;
                }
            }
            labelInfo.Text = "Getting file list...";
            Refresh();
            try
            {
                Cursor    = Cursors.WaitCursor;
                _fileList = api.GetFiles(string.Empty);
                Cursor    = Cursors.Default;
            }
            catch (Exception exception)
            {
                Cursor = Cursors.Default;
                _connectTries++;
                PluginForm_Shown(sender, e);
                _connectTries++;
                if (_connectTries < 2)
                {
                    PluginForm_Shown(sender, e);
                    return;
                }
                MessageBox.Show(exception.Message);
                buttonOK.Enabled = false;
                return;
            }
            labelInfo.Text = string.Empty;
            MakeDescriptionPrompt();
        }
示例#3
0
 public Task <OAuth2Token> RefreshTokenAsync(OAuth2Token oldToken, CancellationToken cancelationToken = default)
 {
     throw new NotImplementedException();
 }
 public InMemoryOAuth2TokenStore()
 {
     _token = null;
 }
 public void OnTokenUpdated(string access_token, string refresh_token, DateTime expires_in)
 {
     _token = new OAuth2Token(access_token, "bearer", null, refresh_token);
 }
 public async Task<ViewResult> Index()
 {
     OAuth2Token token = await AuthSession.InitializeToken();
     return View("Index");
 }
示例#7
0
        // Async task to renew Token
        public async Task <OAuth2Token> RenewToken(OAuth2Token oldToken)
        {
            var token = await _viagogoClient.OAuth2.RefreshAccessTokenAsync(oldToken);

            return(token);
        }
 public TwitterManager()
 {
     _token = OAuth2.GetToken("AhgErASKehSwA3Ktsaw1A", "GqerOT4WN9PnrWaHhz3U8Vqr28Lp3ZGPTzRb9JSL8Lg");
 }
        public static async Task <OAuth2Token> GenerateBearerTokens()
        {
            var apponly = await OAuth2.GetTokenAsync(consumerKey : TwitterApiKey.ConsumerKey, consumerSecret : TwitterApiKey.ConsumerSecret);

            return(OAuth2Token.Create(consumerKey: TwitterApiKey.ConsumerKey, consumerSecret: TwitterApiKey.ConsumerSecret, bearer: apponly.BearerToken));
        }
 /// <summary>
 /// Used primarily for testing purposes to we can keep LastGoodToken private
 /// </summary>
 /// <param name="reference">an OAuth2Token with which we compare</param>
 /// <returns></returns>
 public bool ValidateLastGoodTokenIsEqual(OAuth2Token reference)
 {
     return(_lastGoodToken != null && _lastGoodToken.Equals(reference));
 }
示例#11
0
 public TwitterClient(OAuth2Token token)
 {
     _token = token;
 }
示例#12
0
 /// <summary>
 /// 刷新Token
 /// </summary>
 /// <returns></returns>
 public async Task<OAuth2Token> RefreshToken(string refreshToken)
 {
     DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
         Convert.ToBase64String(Encoding.UTF8.GetBytes(ClientId + ":" + ClientSecret)));
     IDictionary<string, string> paramters = new Dictionary<string, string>();
     paramters.Add(GrantTypes.RefreshToken);
     paramters.Add("refresh_token", refreshToken);
     HttpResponseMessage response = await this.PostAsync(TokenPath, new FormUrlEncodedContent(paramters));
     JObject obj = await response.Content.ReadAsAsync<JObject>();
     OAuth2Token token = new OAuth2Token(obj);
     DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
     return token;
 }
示例#13
0
        public async Task <IActionResult> UploadFile(string type = "image")
        {
            await CheckIsSignoutedAsync();

            // Get file Upload from HttpRequest FormData
            FileModel postedFile = Request.File();

            // Check has file
            if (postedFile == null)
            {
                throw new ApiException("File không tồn tại, Vui lòng chọn lại file!", (int)HttpStatusCode.BadRequest);
            }

            // is upload image
            if (type == "image")
            {
                postedFile.Name = "image";
                // Extention image
                if (!AcceptedImageFormats.MineTypes.Contains(postedFile.ContentType.ToLower()))
                {
                    throw new ApiException($"File chỉ hỗ trợ định dạng {string.Join(",", AcceptedImageFormats.MineTypes)}", (int)HttpStatusCode.BadRequest);
                }
                // Photo FileSize Upto 10 MB
                if (postedFile.Length > 10 * 1024 * 1024)
                {
                    throw new ApiException("Dung lượng file ảnh không được vượt quá 10 MB!", (int)HttpStatusCode.BadRequest);
                }
            }
            // is upload video
            else if (type == "video")
            {
                postedFile.Name = "video";
                // Extention Video
                if (!AcceptedVideoFormats.MineTypes.Contains(postedFile.ContentType.ToLower()))
                {
                    throw new ApiException($"File chỉ hỗ trợ định dạng {string.Join(",", AcceptedVideoFormats.MineTypes)}", (int)HttpStatusCode.BadRequest);
                }
                // Photo FileSize Upto 10 MB
                if (postedFile.Length > 200 * 1024 * 1024)
                {
                    throw new ApiException("Dung lượng file video không được vượt quá 200 MB!", (int)HttpStatusCode.BadRequest);
                }
            }
            // not support media type
            else
            {
                throw new ApiException("not support media type", (int)HttpStatusCode.BadRequest);
            }

            // Save postedFile to ImgUr API
            try
            {
                var client = new ImgurClient(this.imgUrUploadSettings.ClientID, this.imgUrUploadSettings.ClientSecret);
                // state=#access_token=d9cb9143c19c67696e26f4ac59b2f7424af7650c&expires_in=315360000&token_type=bearer&refresh_token=ddd479acc0fa1b91b099599f864ac0a9afa82801&account_username=ngnamB&account_id=96736173
                var token = new OAuth2Token(
                    accessToken: "d9cb9143c19c67696e26f4ac59b2f7424af7650c",
                    refreshToken: "ddd479acc0fa1b91b099599f864ac0a9afa82801",
                    tokenType: "bearer",
                    accountId: "96736173",
                    accountUsername: "******",
                    expiresIn: 315360000);
                //var endpoint = new OAuth2Endpoint(client);
                //var token = endpoint.GetTokenByRefreshTokenAsync("REFRESH_TOKEN");
                client.SetOAuth2Token(token);
                var albumEndpoint = new AlbumEndpoint(client);
                // https://imgur.com/a/Dsoqayj
                IAlbum album = await albumEndpoint.GetAlbumAsync("Dsoqayj");

                var    imageEndpoint = new ImageEndpoint(client);
                IImage imageOrVideo  = await imageEndpoint.UploadImageBinaryAsync(image : postedFile.Bytes, albumId : album.Id);

                //Debug.Write("Image retrieved. Image Url: " + image.Link);
                return(Ok(imageOrVideo));
            }
            catch (ImgurException imgurEx)
            {
                _logger.LogError("UploadFile---", imgurEx);
#if !DEBUG
                throw new ApiException("An error occurred getting an image from Imgur.");
#else
                throw new ApiException(imgurEx);
#endif
            }
        }
示例#14
0
 private void SetupPactForGettingExistingAdvertisement(string givenStatement, string link, OAuth2Token oAuth2Token, AllFieldsInitializer builderInitializer,
                                                       string advertisementId, string viewRenderedAdvertisementLink)
 {
     this.Fixture.MockProviderService
     .Given(givenStatement)
     .UponReceiving("a GET advertisement request")
     .With(new ProviderServiceRequest
     {
         Method  = HttpVerb.Get,
         Path    = link,
         Headers = new Dictionary <string, object>
         {
             { "Authorization", "Bearer " + oAuth2Token.AccessToken },
             { "Accept", $"{ResponseContentTypes.AdvertisementVersion1}, {ResponseContentTypes.AdvertisementErrorVersion1}" },
             { "User-Agent", AdPostingApiFixture.UserAgentHeaderValue }
         }
     })
     .WillRespondWith(new ProviderServiceResponse
     {
         Status  = 200,
         Headers = new Dictionary <string, object>
         {
             { "Content-Type", ResponseContentTypes.AdvertisementVersion1 },
             { "Processing-Status", "Completed" },
             { "X-Request-Id", RequestId }
         },
         Body = new AdvertisementResponseContentBuilder(builderInitializer)
                .WithId(advertisementId)
                .WithState(AdvertisementState.Open.ToString())
                .WithLink("self", link)
                .WithLink("view", viewRenderedAdvertisementLink)
                .WithAgentId(null)
                .WithAdditionalProperties(AdditionalPropertyType.ResidentsOnly.ToString(), AdditionalPropertyType.Graduate.ToString())
                .Build()
     });
 }
        public AdPostingApiClient GetClient(OAuth2Token token)
        {
            var oAuthClient = Mock.Of <IOAuth2TokenClient>(c => c.GetOAuth2TokenAsync() == Task.FromResult(token));

            return(new AdPostingApiClient(this.AdPostingApiServiceBaseUri, oAuthClient));
        }
示例#16
0
        public override bool AcquireOAuth2Token(Identity identity, OAuth2Challenge challenge, OAuth2Token token)
        {
            string accessToken = tokenProvider.AcquireToken(identity.Email, challenge.Authority, challenge.Resource);

            token.AccessToken = accessToken;
            return(true);
        }
 public Task AddTokenAsync(OAuth2Token token)
 {
     return(Task.FromResult(memoryCache.Set(KEY_NAME, token)));
 }
 public Task DeleteTokenAsync()
 {
     _token = null;
     return(Task.FromResult(0));
 }
 private async Task <OAuth2Token> GetOAuth2TokenAsync(OAuth2Token currentOAuth2Token)
 {
     return(currentOAuth2Token == this._oAuth2Token
         ? (this._oAuth2Token = await this._tokenClient.GetOAuth2TokenAsync())
         : this._oAuth2Token);
 }
        /// <summary>
        /// Writes the specified token to Azure Storage
        /// </summary>
        /// <param name="token">The token to save</param>
        /// <returns></returns>
        protected override bool SaveTokenToStore(OAuth2Token token)
        {
            try
            {
                TableOperation op = TableOperation.InsertOrReplace((OAuth2AzureTokenData)token.TokenData);
                table.Execute(op);

                OAuth2TokenReference reference = new OAuth2TokenReference(token.ConsumerKey, token.ConsumerSecret, token.AccessToken);
                TableOperation op2 = TableOperation.InsertOrReplace(reference);
                table.Execute(op2);

                return true;
            }
            catch (Exception ex)
            {
                Logger.Error("SaveToken Failed", ex);
                return false;
            }
        }