public void SaveCookies()
 {
     if (_account != null)
     {
         _accountStore.Save(_account, ServiceId);
     }
 }
Пример #2
0
        /// <summary>
        /// Adds a credential to the Credential Locker.
        /// </summary>
        /// <param name="resource">The resource for which the credentials are used.</param>
        /// <param name="userName">The user name that must be present in the credentials.</param>
        /// <param name="password">The password for the created credentials.</param>
        /// <exception cref="ArgumentNullException">Dispatched when <paramref name="resource"/>, <paramref name="userName"/> or
        /// <paramref name="password"/> is <c>Null</c>
        /// </exception>
        public bool CreateAccount(string resource, string userName, string password)
        {
            if (string.IsNullOrEmpty(resource))
            {
                throw new ArgumentNullException(nameof(resource), "The argument is null");
            }
            if (string.IsNullOrEmpty(userName))
            {
                throw new ArgumentNullException(nameof(userName), "The argument is null");
            }
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException(nameof(password), "The argument is null");
            }

            try
            {
                account = new Account {
                    Username = userName
                };
                account.Properties.Add(resource, password);
                vault.Save(account, AppName);

                var lista = vault.FindAccountsForService(AppName);

                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
Пример #3
0
        async void RefreshButtonClicked(object sender, EventArgs e)
        {
            var refreshToken = account.Properties["refresh_token"];

            if (string.IsNullOrWhiteSpace(refreshToken))
            {
                return;
            }

            var queryValues = new Dictionary <string, string>
            {
                { "refresh_token", refreshToken },
                { "client_id", ServerInfo.ClientId },
                { "grant_type", "refresh_token" },
                { "client_secret", ServerInfo.ClientSecret },
            };

            var authenticator = new OAuth2Authenticator
                                (
                ServerInfo.ClientId,
                ServerInfo.ClientSecret,
                "profile",
                ServerInfo.AuthorizationEndpoint,
                ServerInfo.RedirectionEndpoint,
                ServerInfo.TokenEndpoint,
                null,
                isUsingNativeUI: true
                                );

            try
            {
                var result = await authenticator.RequestAccessTokenAsync(queryValues);

                if (result.ContainsKey("access_token"))
                {
                    account.Properties["access_token"] = result["access_token"];
                }

                if (result.ContainsKey("refresh_token"))
                {
                    account.Properties["refresh_token"] = result["refresh_token"];
                }

                store.Save(account, ServiceId);

                statusText.Text = "Refresh succeeded";
            }
            catch (Exception ex)
            {
                statusText.Text = "Refresh failed " + ex.Message;
            }

            return;
        }
Пример #4
0
 public bool Save(string keyString, string valueString)
 {
     try
     {
         _account.Properties?.Add(keyString, valueString);
         _accountStore.Save(_account, _serviceIdstring);
         return(true);
     }
     catch (AccountStoreException exception)
     {
         Console.WriteLine(exception.StackTrace);
         return(false);
     }
 }
Пример #5
0
        public bool LoginToAccount(string username, string password)
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return(false);
            }

            AccountStore store   = AccountStore.Create();
            Account      account = GetAccountFromStore(AccountStore.Create(), username);

            if (account == null)
            {
                return(false);
            }

            byte[] salt, hashedPassword;

            // Upgrade existing passwords to our new format.
            if (!account.Properties.ContainsKey(saltKey))
            {
                salt                      = CryptoUtilities.Get256BitSalt();
                hashedPassword            = CryptoUtilities.GetKeyDerivation(CryptoUtilities.StringToByteArray(account.Properties[pwKey]), salt);
                account.Properties[pwKey] = Convert.ToBase64String(hashedPassword);
                account.Properties.Add(saltKey, Convert.ToBase64String(salt));
                store.Save(account, serviceID);
            }

            salt           = Convert.FromBase64String(account.Properties[saltKey]);
            hashedPassword = CryptoUtilities.GetKeyDerivation(CryptoUtilities.StringToByteArray(password), salt);

            return(account.Properties[pwKey] == Convert.ToBase64String(hashedPassword));
        }
Пример #6
0
 public void SaveAccount(Account account)
 {
     accountStore.Save(account, OAUTH_SERVICE_NAME);
     _Token = account.Properties ["access_token"];
     // broadcast a message that authentication was successful
     MessagingCenter.Send <App> (this, "Authenticated");
 }
Пример #7
0
        void OnAuthCompleted(object sender, AuthenticatorCompletedEventArgs e)
        {
            var authenticator = sender as OAuth2Authenticator;

            if (authenticator != null)
            {
                authenticator.Completed -= OnAuthCompleted;
                authenticator.Error     -= OnAuthError;
            }

            if (e.IsAuthenticated)
            {
                if (this.account != null)
                {
                    store.Delete(this.account, ServiceId);
                }

                store.Save(account = e.Account, ServiceId);

                statusText.Text = "Authentication succeeded";
            }
            else
            {
                statusText.Text = "Authentication failed";
            }
        }
        public void StoreTokenInSecureStore(MobileServiceUser user)
        {
            var account = new Account(user.UserId);

            account.Properties.Add("token", user.MobileServiceAuthenticationToken);
            AccountStore.Save(account, "tasklist");
        }
Пример #9
0
        /// <summary>
        /// Register new or save old account
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        public async Task <bool> SaveCredentials(string userName, string password, string email)
        {
            if (AreDetailsValid(userName, password))
            {
                //Check if exist
                var account = await GetAccount(userName);

                if (account != null)
                {
                    account.Properties["Password"] = password;
                    account.Properties["Email"]    = email;
                }
                else
                {
                    account = new Account {
                        Username = userName
                    };
                    account.Properties.Add("Password", password);
                    account.Properties.Add("Email", email);
                }

                store.Save(account, App.AppName);

                return(true);
            }

            return(false);
        }
Пример #10
0
        public void saveToken(AuthToken token)
        {
            clearTokens();

            var newAccount = new Account();

            newAccount.Username = token.accessToken;
            if (token.expiresIn != null)
            {
                newAccount.Properties.Add("exires_in", token.expiresIn);
            }
            if (token.tokenType != null)
            {
                newAccount.Properties.Add("token_type", token.tokenType);
            }
            if (token.scope != null)
            {
                newAccount.Properties.Add("scope", token.scope);
            }
            if (token.refreshToken != null)
            {
                newAccount.Properties.Add("refresh_token", token.refreshToken);
            }
            store.Save(newAccount, context);
        }
Пример #11
0
        private void StoreTokenInSecureStore(MobileServiceUser user)
        {
            var account = new Account(user.UserId);

            account.Properties.Add(AppUrlConsts.AppUserTokenKey, user.MobileServiceAuthenticationToken);
            _accountStore.Save(account, AppUrlConsts.AppServiceId);
        }
Пример #12
0
        public bool CreateAndSaveAccount(string username, string password)
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return(false);
            }

            byte[] salt           = CryptoUtilities.Get256BitSalt();
            byte[] hashedPassword = CryptoUtilities.GetKeyDerivation(CryptoUtilities.StringToByteArray(password), salt);

            AccountStore store = AccountStore.Create();

            if (GetAccountFromStore(store, username) != null)
            {
                return(false);
            }

            Account account = new Account(username);

            account.Properties.Add(pwKey, Convert.ToBase64String(hashedPassword));
            account.Properties.Add(saltKey, Convert.ToBase64String(salt));
            store.Save(account, serviceID);

            return(true);
        }
Пример #13
0
        public void StoreTokenInSecureStore(RefreshTokenInfo user)
        {
            ClearSecureStore();
            var account = new Account(user.UserId);

            account.Properties.Add("token", user.RefreshToken);
            account.Properties.Add("provider", user.Provider);
            _accountStore.Save(account, _serviceId);
        }
Пример #14
0
        public void StoreTokenInSecureStore(string userId, string key, string token = "")
        {
            if (storeAccount == null)
            {
                storeAccount = AccountStore.Create();
            }
            var account = new Account(userId);

            account.Properties.Add("token", token);
            storeAccount.Save(account, key);
        }
Пример #15
0
        public void Save(long userId, string userName, string secret, AuthorizationType authorizationType, OrganizationLink organization)
        {
            var props = new Dictionary <string, string>();

            props.Add("UserName", userName);
            props.Add("Secret", secret);
            props.Add("AuthorizationType", authorizationType.ToString());
            props.Add("Organization", organization.ToJsonOrEmptyString());
            props.Add("AvatarUrl", userId.ToString().AsAvatarUrl(organization.HostName));

            _accountStore.Save(new Account(userId.ToString(), props), _applicationSettings.AppName);
        }
Пример #16
0
 public void SaveCredentials(string userName, string password)
 {
     if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
     {
         DeleteCredentials();
         Account account = new Account
         {
             Username = userName
         };
         account.Properties.Add("Password", password);
         _accountStore.Save(account, _AppName);
     }
 }
        private void AccountStoreTests(AuthenticatorCompletedEventArgs ee)
        {
            AccountStore account_store = AccountStore.Create();

            account_store.Save(ee.Account, provider);
            Account account1 = account_store.FindAccountsForService(provider).FirstOrDefault();

            AccountStore.Create().Save(ee.Account, provider + ".v.2");
            // throws on iOS
            //
            Account account2 = AccountStore.Create().FindAccountsForService(provider + ".v.2").FirstOrDefault();

            return;
        }
Пример #18
0
        protected override void OnElementChanged(ElementChangedEventArgs <Page> e)
        {
            base.OnElementChanged(e);

            // this is a ViewGroup - so should be able to load an AXML file and FindView<>
            var          activity = this.Context as Activity;
            AccountStore store    = AccountStore.Create(this.Context);

            try
            {
                OAuth2Authenticator auth = new OAuth2Authenticator(
                    Constants.ClientId,                  // your OAuth2 client id
                    Constants.Scope,                     // the scopes for the particular API you're accessing, delimited by "+" symbols
                    new Uri(Constants.AuthorizeUrl),     // the auth URL for the service
                    new Uri(Constants.RedirectUrl));     // the redirect URL for the service

                auth.Completed += (sender, eventArgs) =>
                {
                    if (eventArgs.IsAuthenticated)
                    {
                        // Use eventArgs.Account to do wonderful things
                        //App.CredManager.DeleteCredentials();
                        store.Save(eventArgs.Account, Constants.AppName);

                        App.SuccessfulLoginAction.Invoke();
                    }
                    else                     // Authentication failed
                    {
                        Toast.MakeText(this.Context, "Authentication Failed", ToastLength.Long).Show();
                    }
                };


                Account savedAccount = store.FindAccountsForService(Constants.AppName).FirstOrDefault();
                if (savedAccount != null)
                {
                    //TODO: check tokens expired? may not be needed bc this is the login page so they couldnt be. should check for login at login button click
                }
                else
                {
                    activity.StartActivity(auth.GetUI(activity));
                };
            }
            catch (Exception ex)
            {
                Toast.MakeText(this.Context, "Error logging in", ToastLength.Long).Show();
            }
        }
Пример #19
0
        protected override void StoreCredentials(string username, string userid, string usertoken, int accountId)
        {
            base.StoreCredentials(username, userid, usertoken, accountId);

            Dictionary <String, String> accountOptions = new Dictionary <String, String>();

            accountOptions.Add(USER_TOKEN_KEY, usertoken);
            accountOptions.Add(USER_ID_KEY, userid);
            accountOptions.Add(USERNAME_ID_KEY, username);
            accountOptions.Add(USER_TRAVELER_ID_KEY, accountId.ToString());

            Account account = new Account(username, accountOptions);

            AccountStore acStore = AccountStore.Create(context);

            acStore.Save(account, SERVICE_ID);
        }
Пример #20
0
        private async Task SaveAccessToken(string normalizedUsername, string serviceId, AccessToken accessToken,
                                           CancellationToken cancellationToken)
        {
            await Task.Factory.StartNew(
                () =>
            {
                var account = _accountStore.FindAccountsForService(serviceId).FirstOrDefault(a => string.Equals(a.Username, normalizedUsername,
                                                                                                                StringComparison.CurrentCultureIgnoreCase));

                if (account != null)
                {
                    _accountStore.Delete(account, serviceId);
                }
                _accountStore.Save(new Account(normalizedUsername, accessToken.ToDictionary()), serviceId);
            },
                cancellationToken).ConfigureAwait(false);
        }
Пример #21
0
        public bool CreateAndSaveAccount(string username, string password)
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return(false);
            }

            AccountStore store = AccountStore.Create();

            if (GetAccountFromStore(store, username) != null)
            {
                return(false);
            }

            Account account = new Account(username);

            account.Properties.Add(pwKey, password);
            store.Save(account, serviceID);

            return(true);
        }
Пример #22
0
        void OnAuthCompleted(object sender, AuthenticatorCompletedEventArgs e)
        {
            var authenticator = sender as OAuth2Authenticator;

            if (authenticator != null)
            {
                authenticator.Completed -= OnAuthCompleted;
                authenticator.Error     -= OnAuthError;
            }

            if (e.IsAuthenticated)
            {
                getProfileButton.IsEnabled = true;

                if (this.account != null)
                {
                    store.Delete(this.account, ServiceId);
                }

                store.Save(account = e.Account, ServiceId);

                getProfileButton.IsEnabled = true;

                if (account.Properties.ContainsKey("expires_in"))
                {
                    var expires = int.Parse(account.Properties ["expires_in"]);
                    statusText.Text = "Token lifetime is: " + expires + "s";
                }
                else
                {
                    statusText.Text = "Authentication succeeded";
                }
            }
            else
            {
                statusText.Text = "Authentication failed";
            }
        }
Пример #23
0
        async void OnAuthCompleted(object sender, AuthenticatorCompletedEventArgs e)
        {
            var authenticator = sender as OAuth2Authenticator;

            if (authenticator != null)
            {
                authenticator.Completed -= OnAuthCompleted;
                authenticator.Error     -= OnAuthError;
            }

            if (e.IsAuthenticated)
            {
                // If the user is authenticated, request their basic user data from Google
                // UserInfoUrl = https://www.googleapis.com/oauth2/v2/userinfo
                var request  = new OAuth2Request("GET", new Uri(Constants.UserInfoUrl), null, e.Account);
                var response = await request.GetResponseAsync();

                if (response != null)
                {
                    // Deserialize the data and store it in the account store
                    // The users email address will be used to identify data in SimpleDB
                    string userJson = await response.GetResponseTextAsync();

                    App.User = JsonConvert.DeserializeObject <User>(userJson);
                }

                if (account != null)
                {
                    store.Delete(account, Constants.AppName);
                }

                store.Save(account = e.Account, Constants.AppName);
                Navigation.InsertPageBefore(new TodoListPage(), this);
                await Navigation.PopToRootAsync();
            }
        }
Пример #24
0
 public void SaveAccountInSecureStore(Account account)
 {
     AccountStore.Save(account, Locations.AppName);
 }
        private void AccountStoreTests(object authenticator, AuthenticatorCompletedEventArgs ee)
        {
            AccountStore account_store = AccountStore.Create();

            account_store.Save(ee.Account, provider);
            // https://kb.xamarin.com/agent/case/225411

            //------------------------------------------------------------------
            // Android
            // cannot reproduce
            Account account1 = account_store.FindAccountsForService(provider).FirstOrDefault();

            if (null != account1)
            {
                //------------------------------------------------------------------
                string token = default(string);
                if (null != account1)
                {
                    string token_name = default(string);
                    Type   t          = authenticator.GetType();
                    if (t == typeof(Xamarin.Auth._MobileServices.OAuth2Authenticator))
                    {
                        token_name = "access_token";
                        token      = account1.Properties[token_name].ToString();
                    }
                    else if (t == typeof(Xamarin.Auth._MobileServices.OAuth1Authenticator))
                    {
                        token_name = "oauth_token";
                        token      = account1.Properties[token_name].ToString();
                    }
                }
                //------------------------------------------------------------------
            }
            //------------------------------------------------------------------

            AccountStore.Create().Save(ee.Account, provider + ".v.2");

            //------------------------------------------------------------------
            // throws on iOS
            //
            Account account2 = AccountStore.Create().FindAccountsForService(provider + ".v.2").FirstOrDefault();

            if (null != account2)
            {
                //------------------------------------------------------------------
                string token = default(string);
                if (null != account2)
                {
                    string token_name = default(string);
                    Type   t          = authenticator.GetType();
                    if (t == typeof(Xamarin.Auth._MobileServices.OAuth2Authenticator))
                    {
                        token_name = "access_token";
                        token      = account2.Properties[token_name].ToString();
                    }
                    else if (t == typeof(Xamarin.Auth._MobileServices.OAuth1Authenticator))
                    {
                        token_name = "oauth_token";
                        token      = account2.Properties[token_name].ToString();
                    }
                }
                //------------------------------------------------------------------
            }
            //------------------------------------------------------------------

            return;
        }
        private void AccountStoreTests(object authenticator, AuthenticatorCompletedEventArgs ee)
        {
            // Step 4.2 Store the account
            AccountStore account_store = AccountStore.Create();

            account_store.Save(ee.Account, provider);

            try
            {
                // Stp 4.3 Retrieve stored accounts
                IEnumerable <Account> accounts = account_store.FindAccountsForService(provider);
                Account account1 = accounts.FirstOrDefault();
                //------------------------------------------------------------------
                if (null != account1)
                {
                    string token      = default(string);
                    string token_name = default(string);
                    Type   t          = authenticator.GetType();
                    if (t == typeof(Xamarin.Auth.OAuth2Authenticator))
                    {
                        token_name = "access_token";
                        token      = account1.Properties[token_name].ToString();
                    }
                    else if (t == typeof(Xamarin.Auth.OAuth1Authenticator))
                    {
                        token_name = "oauth_token";
                        token      = account1.Properties[token_name].ToString();
                    }
                    UIAlertView alert =
                        new UIAlertView
                        (
                            "Token 1",
                            "access_token = " + token,
                            null,
                            "OK",
                            null
                        );
                    alert.Show();
                }
            }
            catch (System.Exception exc)
            {
                // Xamarin.iOS
                // exc  {System.ArgumentNullException: Value cannot be null.
                //  Parameter name: data
                //      at Foundation.NSString.Fr…} System.ArgumentNullException
                // Value cannot be null.
                // Parameter name: data
                string msg = exc.Message;
                System.Diagnostics.Debug.WriteLine("Exception AccountStore: " + msg);
            }

            try
            {
                AccountStore.Create().Save(ee.Account, provider + ".v.2");
            }
            catch (System.Exception exc)
            {
                string msg = exc.Message;
                System.Diagnostics.Debug.WriteLine("Exception AccountStore: " + msg);
            }

            try
            {
                //------------------------------------------------------------------
                // Xamarin.iOS - throws
                IEnumerable <Account> accounts = account_store.FindAccountsForService(provider + ".v.2");
                Account account2 = accounts.FirstOrDefault();
                //------------------------------------------------------------------
                if (null != account2)
                {
                    string token      = default(string);
                    string token_name = default(string);
                    Type   t          = authenticator.GetType();
                    if (t == typeof(Xamarin.Auth.OAuth2Authenticator))
                    {
                        token_name = "access_token";
                        token      = account2.Properties[token_name].ToString();
                    }
                    else if (t == typeof(Xamarin.Auth.OAuth1Authenticator))
                    {
                        token_name = "oauth_token";
                        token      = account2.Properties[token_name].ToString();
                    }
                    UIAlertView alert = new UIAlertView
                                        (
                        "Token 2",
                        "access_token = " + token,
                        null,
                        "OK",
                        null
                                        );
                    alert.Show();
                }
            }
            catch (System.Exception exc)
            {
                string msg = exc.Message;
                System.Diagnostics.Debug.WriteLine("Exception AccountStore: " + msg);
            }

            return;
        }
 private Task SaveAccessToken(string normalizedUsername, string serviceId, AccessToken accessToken, CancellationToken cancellationToken)
 {
     return(Task.Factory.StartNew(() => _accountStore.Save(new Account(normalizedUsername, accessToken.ToDictionary()), serviceId), cancellationToken));
 }
Пример #28
0
 private void SaveAccount()
 {
     AccountStore.Save(_account, Constants.SERVICE_ID);
 }
Пример #29
0
        async void OnAuthCompleted(object sender, AuthenticatorCompletedEventArgs e)
        {
            StaticMethods.ShowLoader();
            var authenticator = sender as OAuth2Authenticator;

            if (authenticator != null)
            {
                authenticator.Completed -= OnAuthCompleted;
                authenticator.Error     -= OnAuthError;
            }

            try
            {
                if (e.IsAuthenticated)
                {
                    // If the user is authenticated, request their basic user data from Google
                    var UserInfoUrlFacebook = "https://graph.facebook.com/me?fields=email,first_name,last_name";
                    var UserInfoUrl         = "https://www.googleapis.com/oauth2/v2/userinfo";
                    var GetUserDataUrl      = string.Empty;
                    if (flag)
                    {
                        GetUserDataUrl = UserInfoUrlFacebook;
                    }
                    else
                    {
                        GetUserDataUrl = UserInfoUrl;
                    }

                    var request  = new OAuth2Request("GET", new Uri(GetUserDataUrl), null, e.Account);
                    var response = await request.GetResponseAsync();

                    if (response != null)
                    {
                        // Deserialize the data and store it in the account store
                        // The users email address will be used to identify data in SimpleDB
                        string userJson = await response.GetResponseTextAsync();

                        if (userJson != "Not Found")
                        {
                            App.User = JsonConvert.DeserializeObject <User>(userJson);
                        }
                    }

                    if (account != null)
                    {
                        store.Delete(account, Constants.AppName);
                    }

                    store.Save(account = e.Account, Constants.AppName);
                    if (App.User.Email != null)
                    {
                        SignUp(App.User).Wait();
                    }
                    //App.Current.MainPage = new NavigationPage(new MainPage());
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                StaticMethods.DismissLoader();
            }
            //Navigation.InsertPageBefore(new HomePage(), this);
            //await Navigation.PopToRootAsync();
        }
        private async void AccountStoreTests(object authenticator, AuthenticatorCompletedEventArgs ee)
        {
            string title = "AccountStore tests";
            string msg   = "";

            AccountStore account_store = AccountStore.Create();

            account_store.Save(ee.Account, provider);

            //------------------------------------------------------------------
            // Android
            // https://kb.xamarin.com/agent/case/225411
            // cannot reproduce
            Account account1 = account_store.FindAccountsForService(provider).FirstOrDefault();

            if (null != account1)
            {
                //------------------------------------------------------------------
                string token = default(string);
                if (null != account1)
                {
                    string token_name = default(string);
                    Type   t          = authenticator.GetType();
                    if (t == typeof(Xamarin.Auth.OAuth2Authenticator))
                    {
                        token_name = "access_token";
                        token      = account1.Properties[token_name].ToString();
                    }
                    else if (t == typeof(Xamarin.Auth.OAuth1Authenticator))
                    {
                        token_name = "oauth_token";
                        token      = account1.Properties[token_name].ToString();
                    }
                }
                //------------------------------------------------------------------
                MessageDialog md = new MessageDialog(msg, title);
                await md.ShowAsync();
            }
            //------------------------------------------------------------------

            AccountStore.Create().Save(ee.Account, provider + ".v.2");

            //------------------------------------------------------------------
            // throws on iOS
            //
            Account account2 = AccountStore.Create().FindAccountsForService(provider + ".v.2").FirstOrDefault();

            if (null != account2)
            {
                //------------------------------------------------------------------
                string token = default(string);
                if (null != account2)
                {
                    string token_name = default(string);
                    Type   t          = authenticator.GetType();
                    if (t == typeof(Xamarin.Auth.OAuth2Authenticator))
                    {
                        token_name = "access_token";
                        token      = account2.Properties[token_name].ToString();
                    }
                    else if (t == typeof(Xamarin.Auth.OAuth1Authenticator))
                    {
                        token_name = "oauth_token";
                        token      = account2.Properties[token_name].ToString();
                    }
                }
                //------------------------------------------------------------------
                MessageDialog md = new MessageDialog
                                   (
                    "access_token = " + token,
                    "Access Token"
                                   );
                await md.ShowAsync();
            }
            //------------------------------------------------------------------

            return;
        }