void TryToLoginByOAuth()
        {
            this.IsBusy = true;
            string clientId     = "Ce0fa0ba8ddd23cb85c24d9c008eb78c92e2fd8caf5034032e41906938263ec04";
            string clientSecret = "9cb4fa305ab61a54e8892e2ee790afe7a8ee5493acdfd04185fb948a1b0b0b35";
            string redirectUri  = "KitchenSink://response";
            string scope        = "spark:all";

            var auth         = new OAuthAuthenticator(clientId, clientSecret, scope, redirectUri);
            var sparkManager = new SparkManager(auth);

            ApplicationController.Instance.CurSparkManager = sparkManager;

            auth.Authorized(r =>
            {
                this.IsBusy = false;
                if (r.IsSuccess)
                {
                    ApplicationController.Instance.ChangeState(State.Main);
                }
                else
                {
                    ApplicationController.Instance.ChangeState(State.LoginByOAuth);
                }
            });
        }
Ejemplo n.º 2
0
        public static AuthenticatedUser LoadCredentials()
        {
            AuthenticatedUser twiUser = new AuthenticatedUser();

            if (!File.Exists(s_configFile))
            {
                string token = OAuthAuthenticator.GetOAuthToken().Result;
                Console.WriteLine("Please open your favorite browser and go to this URL to authenticate with Twitter:");
                Console.WriteLine($"https://api.twitter.com/oauth/authorize?oauth_token={token}");
                Console.Write("Insert the pin here:");

                string pin = Console.ReadLine();

                string accessToken = OAuthAuthenticator.GetPINToken(token, pin).Result;
                twiUser.SerializeTokens(accessToken);
                Console.WriteLine("Sucess!");
                Console.WriteLine("");
            }
            else
            {
                twiUser = Deserialize();
            }

            return(twiUser);
        }
        public void ValidateDefaultOAuthVersionAuthenticator()
        {
            var authenticator = new OAuthAuthenticator("key", "secret");

            var oauthVersion = GetOAuthVersionFromAuthenticator(authenticator);

            Assert.Equal("1.0", oauthVersion);
        }
        public void ValidateOAuthVersionOneZeroAAuthenticator()
        {
            var authenticator = new OAuthAuthenticator("key", "secret", OAuthVersion.OneZeroA);

            var oauthVersion = GetOAuthVersionFromAuthenticator(authenticator);

            Assert.Equal("1.0a", oauthVersion);
        }
        public void ValidateOAuthVersionOmitAuthenticator()
        {
            var authenticator = new OAuthAuthenticator("key", "secret", OAuthVersion.Omit);

            var oauthVersion = GetOAuthVersionFromAuthenticator(authenticator);

            Assert.Null(oauthVersion);
        }
        private string GetOAuthVersionFromAuthenticator(OAuthAuthenticator authenticator)
        {
            var url = authenticator.CreateGetRequestTokenAddress("http://example.com", "GET", "http://example.com/callback");

            return(new Uri(url).Query
                   .Split('&')
                   .Select(parameter => parameter.Split('='))
                   .SingleOrDefault(keyValue => keyValue[0] == "oauth_version")?[1]);
        }
        public void AccessTokenTestNullToken()
        {
            var auth = new OAuthAuthenticator(clientId, clientSecret, scope, redirectUri);

            auth.AccessToken(r =>
            {
                Assert.IsFalse(r.IsSuccess);
            });
        }
        public void OAuthAuthenticatorTest()
        {
            var auth = new OAuthAuthenticator(clientId, clientSecret, scope, redirectUri);

            Assert.IsNotNull(auth);

            string authUrl = "https://idbroker.webex.com/idb/oauth2/v1/authorize?cisKeepMeSignedInOption=1&response_type=code&client_id=C452b978600b789f41d65b6a017f7f8e10c14925af17b1befac2293d107b943ac&redirect_uri=WebexSdkWinUnitTest%3A%2F%2Fredirect";

            Assert.IsTrue(auth.AuthorizationUrl.StartsWith(authUrl));
        }
Ejemplo n.º 9
0
        public void GetOAuthToken()
        {
            try
            {
                string token = OAuthAuthenticator.GetOAuthToken(m_user.AppSettings.AppKey, m_user.AppSettings.AppSecret).Result;

                Assert.True(token.Length == 27, "OK");
            }
            catch (Exception ex)
            {
                Assert.True(false, Util.ExceptionMessage(ex));
            }
        }
Ejemplo n.º 10
0
        public bool Login(string email, string password)
        {
            Http http = new Http("get");
            http.Url = new Uri("https://api.dropbox.com/0/token");

            http.Parameters.Add(new HttpParameter { Name = "oauth_consumer_key", Value = _apiKey });

            http.Parameters.Add(new HttpParameter { Name = "email", Value = email });
            http.Parameters.Add(new HttpParameter { Name = "password", Value = password });

            //add oauth
            OAuthAuthenticator oAuth = new OAuthAuthenticator(http.Url.ToString(), _apiKey, _appsecret, "", "");
            oAuth.Authenticate(http);

            try
            {
                http.Get();

                if (http.Response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    //Wrong Username/Password
                    throw new DropException("Incorrect Username/Password.");
                }

                BytesRecieved += http.Response.Content.Length;

                JsonDeserializer deserializer = new JsonDeserializer();

                UserLogin = deserializer.Deserialize<UserLogin>(http.Response.Content);

                if (!string.IsNullOrEmpty(UserLogin.Error))
                {
                    //Some sort of dropbox error
                    throw new DropException(UserLogin.Error);
                }

                LoggedIn = true;

                return LoggedIn;
            }
            catch (DropException dx)
            {
                throw dx;
            }
            catch (Exception ex)
            {
                return false;
            }

        }
Ejemplo n.º 11
0
        public AuthCodeViewModel(string hostUrl, ITrace trace, IHttpClientFactory httpClientFactory, ISettings settings) : base(hostUrl)
        {
            var authenticator = new OAuthAuthenticator(trace, httpClientFactory, settings);

            AuthenticateCommand = ReactiveCommand.Create <object>(async param =>
            {
                var scopes = BitbucketConstants.BitbucketCredentialScopes;

                AuthenticationResult result = await authenticator.AcquireTokenAsync(
                    settings.RemoteUri, scopes,
                    new ExtendedCredential("not used", "anywhere", "at all"));

                if (result.Type == AuthenticationResultType.Success)
                {
                    trace.WriteLine($"Token acquisition for '{settings.RemoteUri}' succeeded");


                    var usernameResult = await authenticator.AquireUserDetailsAsync(settings.RemoteUri, result.Token.Password);
                    if (usernameResult.Type == AuthenticationResultType.Success)
                    {
                        _output.Add("username", usernameResult.Token.UserName);
                        _output.Add("accesstoken", result.Token.Password);
                        _output.Add("refreshtoken", result.RefreshToken.Password);
                        _output.Add("scheme", result.Token.Scheme);
                        _output.Add("authentication", result.Token.Scheme);

                        Success = true;
                    }
                    else
                    {
                        Success = false;
                    }
                }
                else
                {
                    trace.WriteLine($"Token acquisition for '{settings.RemoteUri}' failed");
                    Success = false;
                }

                // TODO OAuth
                // TODO validate credentials
                Exit();
            });

            CancelCommand = ReactiveCommand.Create <object>(param =>
            {
                Success = false;
                Exit();
            });
        }
        public void AuthorizeTest()
        {
            var auth = new OAuthAuthenticator(clientId, clientSecret, scope, redirectUri);

            string authurl = auth.AuthorizationUrl;

            Console.WriteLine("you need mannul copy the authurl to browser, to get auth code. and then paste the following method parapeter");
            Console.WriteLine("auth url: {0}", authurl);
            //string authcode = "";

            //auth.authorize(authcode, r =>
            //{
            //    Assert.IsTrue(r.Success);
            //});
        }
Ejemplo n.º 13
0
        private async Task <BoxContext> RequireContextAsync(RootName root, string apiKey = null)
        {
            if (root == null)
            {
                throw new ArgumentNullException(nameof(root));
            }

            if (!contextCache.TryGetValue(root, out BoxContext result))
            {
                var client = await OAuthAuthenticator.LoginAsync(root.UserName, apiKey, settingsPassPhrase);

                contextCache.Add(root, result = new BoxContext(client));
            }
            return(result);
        }
Ejemplo n.º 14
0
        //[Fact] Not automatic... it needs the PIN and oAuthToken
        public void GetPINAuthToken()
        {
            try
            {
                string pin          = "3616991";
                string oAuthToken   = "Kn5i6AAAAAAAARPWAAABXHm2bfw";
                string accessTokens = OAuthAuthenticator.GetPINToken(oAuthToken, pin, m_user.AppSettings.AppKey, m_user.AppSettings.AppSecret).Result;

                AuthenticatedUser user = new AuthenticatedUser();
                user.ParseTokens(accessTokens);
            }
            catch (Exception ex)
            {
                Assert.True(false, Util.ExceptionMessage(ex));
            }
        }
        public async Task InitAsync(
            string oauthTokenEndpoint,
            string oauthClientId,
            string oauthClientSecret,
            string oauthResource,
            CancellationToken cancellationToken)
        {
            var bearerToken = await OAuthAuthenticator.GetBearerTokenAsync(oauthTokenEndpoint, oauthClientId, oauthClientSecret, oauthResource,
                                                                           cancellationToken);

            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);

            _giasMappings = await GetSystemEnums(SourceSystemNames.GetInformationAboutSchools, cancellationToken);

            _ukrlpMappings = await GetSystemEnums(SourceSystemNames.UkRegisterOfLearningProviders, cancellationToken);
        }
Ejemplo n.º 16
0
        private async Task <hubiCContext> RequireContextAsync(RootName root, string apiKey = null, string container = DEFAULT_CONTAINER)
        {
            if (root == null)
            {
                throw new ArgumentNullException(nameof(root));
            }

            var result = default(hubiCContext);

            if (!contextCache.TryGetValue(root, out result))
            {
                var client = await OAuthAuthenticator.LoginAsync(root.UserName, apiKey, settingsPassPhrase);

                contextCache.Add(root, result = new hubiCContext(client, container));
            }
            return(result);
        }
Ejemplo n.º 17
0
        private async Task <CopyContext> RequireContext(RootName root, string apiKey = null)
        {
            if (root == null)
            {
                throw new ArgumentNullException(nameof(root));
            }

            var result = default(CopyContext);

            if (!contextCache.TryGetValue(root, out result))
            {
                var client = await OAuthAuthenticator.Login(root.UserName, apiKey);

                contextCache.Add(root, result = new CopyContext(client));
            }
            return(result);
        }
Ejemplo n.º 18
0
        private async Task <OneDriveContext> RequireContextAsync(RootName root, string apiKey = null)
        {
            if (root == null)
            {
                throw new ArgumentNullException(nameof(root));
            }

            var result = default(OneDriveContext);

            if (!contextCache.TryGetValue(root, out result))
            {
                var connection = await OAuthAuthenticator.LoginAsync(root.UserName, apiKey, settingsPassPhrase);

                var drive = await connection.GetDrive();

                contextCache.Add(root, result = new OneDriveContext(connection, drive));
            }
            return(result);
        }
        public void AuthorizeTestInvalidAuthCode()
        {
            var completion = new ManualResetEvent(false);
            var response   = new WebexApiEventArgs();

            var auth = new OAuthAuthenticator(clientId, clientSecret, scope, redirectUri);

            auth.Authorize("a.b.c", r =>
            {
                response = r;
                completion.Set();
            });

            if (!completion.WaitOne(30000))
            {
                Assert.Fail();
            }

            Assert.IsFalse(response.IsSuccess);
        }
Ejemplo n.º 20
0
        public void AuthorizeByOAuthAccessToken(string authCode)
        {
            GettingAuthCode = false;
            IsBusy          = true;

            OAuthAuthenticator auth = ApplicationController.Instance.CurSparkManager.CurAuthenticator as OAuthAuthenticator;

            auth?.Authorize(authCode, result =>
            {
                IsBusy = false;
                if (result.IsSuccess)
                {
                    output("authorize success!");
                    ApplicationController.Instance.ChangeState(State.Main);
                }
                else
                {
                    output("authorize failed!");
                }
            });
        }
Ejemplo n.º 21
0
        public bool Delete(MetaData remoteFile)
        {
            Http http = new Http("get");
            http.Url = new Uri("https://api.dropbox.com/0/fileops/delete");

            OAuthAuthenticator oAuth = new OAuthAuthenticator(http.Url.ToString(), _apiKey, _appsecret, UserLogin.Token, UserLogin.Secret);

            http.Parameters.Add(new HttpParameter { Name = "path", Value = remoteFile.Path });
            http.Parameters.Add(new HttpParameter { Name = "root", Value = "dropbox" });

            oAuth.Authenticate(http);

            try
            {
                http.Get();

                BytesRecieved += http.Response.Content.Length;

                return http.Response.StatusCode == HttpStatusCode.OK;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
Ejemplo n.º 22
0
 public StartPage()
 {
     Content = new StackLayout
     {
         VerticalOptions   = LayoutOptions.Center,
         HorizontalOptions = LayoutOptions.Center,
         Children          =
         {
             new Button
             {
                 Text              = "Authenticate",
                 VerticalOptions   = LayoutOptions.Center,
                 HorizontalOptions = LayoutOptions.Center,
                 Command           = new Command(async() => HandleResult(await OAuthAuthenticator.Authenticate()))
             }
         }
     };
 }
Ejemplo n.º 23
0
 private async static void LoadProviders()
 {
     var assembly = typeof(App).GetTypeInfo().Assembly;
     var stream   = assembly.GetManifestResourceStream(assembly.GetName().Name + ".KeysLocal.json");
     await OAuthAuthenticator.LoadConfiguration(stream);
 }
Ejemplo n.º 24
0
 public void PurgeSettings(RootName root)
 {
     OAuthAuthenticator.PurgeRefreshToken(root?.UserName);
 }
        public void DeauthorizeTest()
        {
            var auth = new OAuthAuthenticator(clientId, clientSecret, scope, redirectUri);

            auth.Deauthorize();
        }
Ejemplo n.º 26
0
        public MetaData GetItems(MetaData remoteDir)
        {
            Http http = new Http("get");
            http.Url = new Uri("https://api.dropbox.com/0/metadata/dropbox" + remoteDir.Path);

            OAuthAuthenticator oAuth = new OAuthAuthenticator(http.Url.ToString(), _apiKey, _appsecret, UserLogin.Token, UserLogin.Secret);

            oAuth.Authenticate(http);

            try
            {
                http.Get();

                BytesRecieved += http.Response.Content.Length;

                JsonDeserializer deserializer = new JsonDeserializer();

                var returnMeta = deserializer.Deserialize<MetaData>(http.Response.Content);

                if (string.IsNullOrEmpty(returnMeta.error))
                {
                    if (returnMeta.Contents == null) returnMeta.Contents = new List<MetaData>();
                    return returnMeta;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }
Ejemplo n.º 27
0
        public DropboxFile GetFile(MetaData remoteFile)
        {
            Http http = new Http("get");
            http.Url = new Uri("https://api-content.dropbox.com/0/files/dropbox" + remoteFile.Path);

            OAuthAuthenticator oAuth = new OAuthAuthenticator(http.Url.ToString(), _apiKey, _appsecret, UserLogin.Token, UserLogin.Secret);

            oAuth.Authenticate(http);

            try
            {
                var localFileInfo = new FileInfo(Settings.Instance.TempDirectory + remoteFile.Name);

                if (!localFileInfo.Directory.Exists) localFileInfo.Directory.Create();

                http.GetAndSaveFile(localFileInfo.FullName);

                BytesRecieved += localFileInfo.Length;
                
                //Check for OK status ;)
                if (http.Response.StatusCode != System.Net.HttpStatusCode.OK) return null;

                return new DropboxFile { Name = remoteFile.Name, Path = remoteFile.Path, LocalFileInfo = localFileInfo };
            }
            catch (Exception ex)
            {
                return null;
            }
        }
Ejemplo n.º 28
0
		public OAuthApi(string identifier, OAuthAuthenticator authenticator, HttpMessageHandler handler = null) : this(identifier, authenticator.ClientId, authenticator.ClientSecret, handler)
		{
			this.authenticator = authenticator;
			TokenUrl = authenticator.TokenUrl;
		}
Ejemplo n.º 29
0
        public AccountInfo GetAccountInfo()
        {
            if (_accountInfo != null)
            {
                var lastDiff = DateTime.Now - _lastAccountInfo;
                //May need Tweeking
                if (lastDiff.TotalSeconds < 100) return _accountInfo;
            }

            Http http = new Http("get");
            http.Url = new Uri("https://api.dropbox.com/0/account/info");

            OAuthAuthenticator oAuth = new OAuthAuthenticator(http.Url.ToString(), _apiKey, _appsecret, UserLogin.Token, UserLogin.Secret);

            oAuth.Authenticate(http);

            try
            {
                http.Get();

                BytesRecieved += http.Response.Content.Length;

                JsonDeserializer deserializer = new JsonDeserializer();

                _accountInfo = deserializer.Deserialize<AccountInfo>(http.Response.Content);

                return _accountInfo;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
Ejemplo n.º 30
0
        public MetaData CreateFolder(MetaData parent, string folderName)
        {
            Http http = new Http("get");
            http.Url = new Uri("https://api.dropbox.com/0/fileops/create_folder");

            OAuthAuthenticator oAuth = new OAuthAuthenticator(http.Url.ToString(), _apiKey, _appsecret, UserLogin.Token, UserLogin.Secret);

            http.Parameters.Add(new HttpParameter { Name = "path", Value = string.Format("{0}/{1}", parent.Path, folderName) });
            http.Parameters.Add(new HttpParameter { Name = "root", Value = "dropbox" });

            oAuth.Authenticate(http);

            try
            {
                http.Get();

                BytesRecieved += http.Response.Content.Length;

                JsonDeserializer deserializer = new JsonDeserializer();

                var returnMeta = deserializer.Deserialize<MetaData>(http.Response.Content);

                if (string.IsNullOrEmpty(returnMeta.error))
                {
                    if (returnMeta.Contents == null) returnMeta.Contents = new List<MetaData>();
                    return returnMeta;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }
Ejemplo n.º 31
0
        public bool UploadFile(FileInfo localFile, MetaData remoteDir)
        {
            var path = remoteDir.Path;
            if (!path.StartsWith("/")) path = "/" + path;

            byte[] buff = null;
            FileStream fs = new FileStream(localFile.FullName, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            long numBytes = localFile.Length;
            buff = br.ReadBytes((int)numBytes);

            Http http = new Http("post");
            http.Url = new Uri("https://api-content.dropbox.com/0/files/dropbox" + path);

            http.Parameters.Add(new HttpParameter { Name = "file", Value = localFile.Name });

            http.Files.Add(new HttpFile { Parameter = "file", FileName = localFile.Name, ContentType = localFile.Extension, Data = buff });

            OAuthAuthenticator oAuth = new OAuthAuthenticator(http.Url.ToString(), _apiKey, _appsecret, UserLogin.Token, UserLogin.Secret);

            oAuth.Authenticate(http);

            try
            {
                http.Post();

                BytesRecieved += http.Response.Content.Length;
                BytesSent += localFile.Length;

                return http.Response.StatusCode == HttpStatusCode.OK;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
Ejemplo n.º 32
0
        private string BuildUrlFromPath(string path)
        {
            string result = "https://api-content.dropbox.com/1/files/dropbox" + Uri.EscapeUriString(path) + "?";

            var authenticator = new OAuthAuthenticator(result,
                                                       "tdjfq9pdclgngyt",
                                                       "k6okn03xb6v5lza",
                                                       this.dropNetClient.UserLogin.Token,
                                                       this.dropNetClient.UserLogin.Secret);
            var authenticatorRequest = new RestSharp.RestRequest();
            authenticator.Authenticate(null, authenticatorRequest);

            bool first = true;
            foreach (var parameter in authenticatorRequest.Parameters)
            {
                if (!first)
                {
                    result += "&";
                }
                else
                {
                    first = false;
                }
                result += parameter.Name.ToString() + "=" + HttpUtility.UrlEncode(parameter.Value.ToString());
            }
            return result;
        }
Ejemplo n.º 33
0
        public bool MoveFile(MetaData fromFile, MetaData toDir)
        {
            Http http = new Http("get");
            http.Url = new Uri("https://api.dropbox.com/0/fileops/move");

            OAuthAuthenticator oAuth = new OAuthAuthenticator(http.Url.ToString(), _apiKey, _appsecret, UserLogin.Token, UserLogin.Secret);

            http.Parameters.Add(new HttpParameter { Name = "root", Value = "dropbox" });
            http.Parameters.Add(new HttpParameter { Name = "from_path", Value = fromFile.Path });
            http.Parameters.Add(new HttpParameter { Name = "to_path", Value = string.Format("{0}/{1}", toDir.Path, fromFile.Name) });

            oAuth.Authenticate(http);

            try
            {
                http.Get();

                BytesRecieved += http.Response.Content.Length;

                return http.Response.StatusCode == HttpStatusCode.OK;
            }
            catch (Exception ex)
            {
                return false;
            }
        }