Beispiel #1
0
        private async Task WiredLogout(Windows.Security.Credentials.PasswordCredential credential)
        {
            var response = await AuthHelper.LogoutAsync(4, currentAccount.Username);

            if (response.Contains("logout_ok"))
            {
                SetLogoutButtonAnimation();
            }
            else if (response == "not_online_error")
            {
                SetLogoutButtonAnimation();
            }
            else
            {
                isOnline = await NetHelper.IsOnline();

                if (isOnline)
                {
                    SetLoginButton();
                }
                else
                {
                    SetLogoutButton();
                }
            }
        }
Beispiel #2
0
        private static void _AddOrUpdateAccount(string mailAddress, string password)
        {
            var id = mailAddress;

            if (String.IsNullOrWhiteSpace(mailAddress) || String.IsNullOrWhiteSpace(password))
            {
                throw new Models.Infrastructure.HohoemaExpception();
            }

            var vault = new Windows.Security.Credentials.PasswordVault();

            try
            {
                var credential = vault.Retrieve(AccountResrouceKey, id);
                vault.Remove(credential);
            }
            catch
            {
            }

            {
                var credential = new Windows.Security.Credentials.PasswordCredential(AccountResrouceKey, id, password);
                vault.Add(credential);
            }
        }
Beispiel #3
0
        private static void _AddOrUpdateAccount(string mailAddress, string password)
        {
            var id = mailAddress;

            if (String.IsNullOrWhiteSpace(mailAddress) || String.IsNullOrWhiteSpace(password))
            {
                throw new Exception();
            }

            var vault = new Windows.Security.Credentials.PasswordVault();

            try
            {
                var credential = vault.Retrieve(nameof(HohoemaApp), id);
                vault.Remove(credential);
            }
            catch
            {
            }

            {
                var credential = new Windows.Security.Credentials.PasswordCredential(nameof(HohoemaApp), id, password);
                vault.Add(credential);
            }
        }
Beispiel #4
0
        public void Store(string key, string value)
        {
            var vault = new Windows.Security.Credentials.PasswordVault();

            var pwdCred = new Windows.Security.Credentials.PasswordCredential()
            {
                Password = value,
                UserName = key,
                Resource = key,
            };


            vault.Add(pwdCred);
        }
Beispiel #5
0
        private static Windows.Security.Credentials.PasswordCredential GetCredentialFromLocker()
        {
            Windows.Security.Credentials.PasswordCredential credential = null;

            var vault          = new Windows.Security.Credentials.PasswordVault();
            var credentialList = vault.RetrieveAll();

            if (credentialList.Count > 0)
            {
                credential = credentialList[0];
            }

            return(credential);
        }
Beispiel #6
0
 private async void RetrieveCredentials()
 {
     Windows.Security.Credentials.PasswordCredential credentials = StorageService.RetrieveUserCredentials();
     if (credentials != null)
     {
         BGGUsername = credentials.UserName;
         BGGPassword = credentials.Password;
         BGGUser     = new UserDataItem(await Client.LoadUserDetails(BGGUsername));
     }
     else
     {
         // TODO Should display error message
     }
 }
        public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
        {
            System.Console.WriteLine("Application service is recalled after 10s");

            SQLiteConnection conn = new SQLiteConnection(DB_Link.conn_link); // to store in SQLite daabase

            string     strurltest    = String.Format("url");                 // fetch API
            WebRequest requestObjGet = WebRequest.Create(strurltest);

            requestObjGet.Method = "GET";
            HttpWebResponse responseObjGet = null;

            responseObjGet = (HttpWebResponse)requestObjGet.GetResponse();

            string strresult = null;                                   // set null

            using (Stream stream = responseObjGet.GetResponseStream()) // in json format
            {
                StreamReader sr = new StreamReader(stream);
                strresult = sr.ReadToEnd();
                sr.Close();
            }

            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            List <Comments> objList = (List <Comments>)serializer.Deserializer(strresult, typeof((List <Comments>)));

            foreach (Comments obj in objList)
            {
                string username = obj.username;
                string password = obj.password;

                SQLiteCommand cmd = new SQLiteCommand("insert into userInfo (user_name,user_pass) values ('" + text_user.Text + "','" + text_pass.Text + "')");
                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();



                var vault      = new Windows.Security.Credentials.PasswordVault();
                var credential = new Windows.Security.Credentials.PasswordCredential(
                    resource: "Sample Application",
                    userName: this.text_username.Text,
                    password: this.text_password.Text);
                vault.Add(credential);

                System.Console.WriteLine("Insertion Done in SQLite......");
            }
        }
        static void GetCredentialFromLocker()
        {
            Windows.Security.Credentials.PasswordCredential credential = null;
            var vault = new Windows.Security.Credentials.PasswordVault();

            credential = vault.Retrieve("My App", "username");
            if (credential != null)
            {
                Console.WriteLine("GetCredentialFromLocker: " + credential.Password);
            }
            else
            {
                Console.WriteLine("Could not retrieve password from PasswordVault");
            }
        }
Beispiel #9
0
        private async Task WiredLogin(Windows.Security.Credentials.PasswordCredential credential)
        {
            var response = await AuthHelper.LoginAsync(4, currentAccount.Username, credential.Password);

            if (response == null)
            {
                return;
            }

            if (response.Contains("login_ok"))
            {
                SetLoginButtonAnimation();
                await GetConnectionStatusAsync();

                var response6 = await AuthHelper.LoginAsync(6, currentAccount.Username, credential.Password);

                if (response6 != null && response6.Contains("login_error"))
                {
                    await Task.Delay(10100);

                    await AuthHelper.LoginAsync(6, currentAccount.Username, credential.Password);
                }
            }
            else if (response == "ip_already_online_error")
            {
                SetLoginButton();
            }
            else if (response == "not_online_error")
            {
                await WirelessLogin();
            }
            else if (response.Contains("login_error"))
            {
                await Task.Delay(10100);
                await LoginNetworkIfFavoriteAsync();
            }
            else
            {
                CredentialHelper.RemoveAccount(App.Accounts[0].Username);

                App.Accounts.RemoveAt(0);
                var localHelper = new LocalObjectStorageHelper();
                await localHelper.SaveFileAsync("Accounts", App.Accounts);

                var rootFrame = Window.Current.Content as Frame;
                rootFrame.Navigate(typeof(WelcomePage));
            }
        }
Beispiel #10
0
        private RTPasswordCredential RTPasswordCredentialFromICredentials(ICredentials creds)
        {
            // The WinRT PasswordCredential object does not have a special credentials value for "default credentials".
            // In general, the UWP HTTP platform automatically manages sending default credentials, if no explicit
            // credential was specified, based on if the app has EnterpriseAuthentication capability and if the endpoint
            // is listed in an intranet zone.
            //
            // A WinRT PasswordCredential object that is either null or created with the default constructor (i.e. with
            // empty values for username and password) indicates that there is no explicit credential. And that means
            // that the default logged-on credentials might be sent to the endpoint.
            //
            // There is currently no WinRT API to turn off sending default credentials other than the capability
            // and intranet zone checks described above. In general, the UWP HTTP model for specifying default
            // credentials is orthogonal to how the .NET System.Net APIs have been designed.
            if (creds == null || creds == CredentialCache.DefaultCredentials)
            {
                return(null);
            }
            else
            {
                Debug.Assert(creds is NetworkCredential);

                NetworkCredential networkCred = (NetworkCredential)creds;

                // Creating a new WinRT PasswordCredential object with the default constructor ends up
                // with empty strings for username and password inside the object. However, one can't assign
                // empty strings to those properties; otherwise, it will throw an error.
                RTPasswordCredential rtCreds = new RTPasswordCredential();
                if (!string.IsNullOrEmpty(networkCred.UserName))
                {
                    if (!string.IsNullOrEmpty(networkCred.Domain))
                    {
                        rtCreds.UserName = networkCred.Domain + "\\" + networkCred.UserName;
                    }
                    else
                    {
                        rtCreds.UserName = networkCred.UserName;
                    }
                }

                if (!string.IsNullOrEmpty(networkCred.Password))
                {
                    rtCreds.Password = networkCred.Password;
                }

                return(rtCreds);
            }
        }
Beispiel #11
0
        private void StartPublisher(WlanSetting setting)
        {
            _publisher = new WiFiDirectAdvertisementPublisher();
            _publisher.Advertisement.ListenStateDiscoverability    = WiFiDirectAdvertisementListenStateDiscoverability.Normal;
            _publisher.Advertisement.IsAutonomousGroupOwnerEnabled = true;
            _publisher.StatusChanged += OnStatusChanged;
            _publisher.Advertisement.LegacySettings.IsEnabled = true;

            var creds = new Windows.Security.Credentials.PasswordCredential();

            _publisher.Advertisement.LegacySettings.Ssid = setting.Name;
            creds.Password = setting.Password;
            _publisher.Advertisement.LegacySettings.Passphrase = creds;

            _publisher.Start();
        }
        public Windows.Security.Credentials.PasswordCredential GetCredentialFromLocker()
        {
            Windows.Security.Credentials.PasswordCredential credential = null;

            var vault          = new Windows.Security.Credentials.PasswordVault();
            var credentialList = vault.FindAllByResource("User");

            if (credentialList.Count > 0)
            {
                if (credentialList.Count == 1)
                {
                    credential = credentialList[0];
                }
            }

            return(credential);
        }
Beispiel #13
0
        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            //Logear al usuario y
            string resourceName = "UWPAppPasswordVault";
            string usuario      = txtNombre.Text;
            string contrasena   = txtPassword.Text;

            Windows.Security.Credentials.PasswordCredential credencial = null;

            //guardarlo en el PassportVault si no existe y es el primero
            //--> recuperar del vault la lista
            var vault = new Windows.Security.Credentials.PasswordVault();
            //Controlar exccepcion cuando esta vacia
            //try**
            var credentialList = vault.RetrieveAll();

            //var credentialList = vault.FindAllByResource(resourceName);
            //--> mirar si esta vacia
            if (credentialList.Count == 0)
            {
                //--> añadirle a la lista
                vault.Add(new Windows.Security.Credentials.PasswordCredential(
                              resourceName, usuario, contrasena));
                Frame.Navigate(typeof(Servicio));
            }
            //Si no es el primero y existe enviarle a Servicio
            //Si no es el primero y no existe mandarle a vienvenida
            if (credentialList.Count > 0)
            {
                //**Si implementamos el try
                //credencial = credentialList.FirstOrDefault();
                credencial = credentialList[0];

                if (credencial.UserName == usuario && credencial.Resource == resourceName)
                {
                    Frame.Navigate(typeof(Servicio));
                }
                else
                {
                    Frame.Navigate(typeof(BienVenida));
                }
            }
        }
Beispiel #14
0
        private Type getProfilePage()
        {
            Windows.Security.Credentials.PasswordCredential credential = null;

            var vault = new Windows.Security.Credentials.PasswordVault();

            try {
                var credentialList = vault.FindAllByResource(AuthViewModel.AUTH_JWT_TOKEN_NS);
                if (credentialList.Count > 0)
                {
                    if (credentialList.Count == 1)
                    {
                        credential = credentialList[0];
                    }
                    else
                    {
                        credential = vault.Retrieve(AuthViewModel.AUTH_JWT_TOKEN_NS, AuthViewModel.AUTH_USERNAME_NS);
                    }
                }
            } catch {
                // do nothing
            }

            if (credential == null)
            {
                return(typeof(AuthContainer));
            }

            credential.RetrievePassword();
            var data     = credential.Password;
            var idAndJWT = data.Split("|");

            if (idAndJWT.Length < 2)
            {
                return(typeof(AuthContainer));
            }
            int uid = -1;

            Int32.TryParse(idAndJWT[0], out uid);
            Config.uid = uid;
            Config.JWT = idAndJWT[1];
            return(typeof(Profile));
        }
        private Windows.Security.Credentials.PasswordCredential GetCredentialFromLocker()
        {
            String defaultUserName;

            Windows.Security.Credentials.PasswordCredential credential = null;

            var vault          = new Windows.Security.Credentials.PasswordVault();
            var credentialList = vault.FindAllByResource(resourceName);

            if (credentialList.Count > 0)
            {
                if (credentialList.Count == 1)
                {
                    credential = credentialList[0];
                }
            }

            return(credential);
        }
Beispiel #16
0
        public MainWindow(ISampleService sampleService, IOptions <AppSettings> settings)
        {
            InitializeComponent();

            this.sampleService = sampleService;
            this.settings      = settings.Value;

            var vault             = new Windows.Security.Credentials.PasswordVault();
            var userKeyCredential = new Windows.Security.Credentials.PasswordCredential(
                resource: "Optimus",
                userName: "******",
                password: "******");

            vault.Add(userKeyCredential);

            var clientIdCredential = new Windows.Security.Credentials.PasswordCredential(
                resource: "Optimus",
                userName: "******",
                password: "******");

            vault.Add(clientIdCredential);
        }
        /// <summary>
        /// Get password of user how wanted to save his connection after closing the app
        /// </summary>
        /// <returns></returns>
        private Windows.Security.Credentials.PasswordCredential GetCredentialFromLocker()
        {
            try
            {
                Windows.Security.Credentials.PasswordCredential credential = null;

                var vault          = new Windows.Security.Credentials.PasswordVault();
                var credentialList = vault.FindAllByResource(resourceName);
                if (credentialList.Count > 0)
                {
                    // There can be more than one user, for now only one is possible [0] > the first one
                    // https://docs.microsoft.com/en-us/windows/uwp/security/credential-locker > pour mettre en place le multit login
                    credential = credentialList[0];
                }

                return(credential);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Fail(ex.ToString());
                return(null);
            }
        }
Beispiel #18
0
        private RTPasswordCredential RTPasswordCredentialFromNetworkCredential(NetworkCredential creds)
        {
            // RTPasswordCredential doesn't allow assigning string.Empty values, but those are the default values.
            RTPasswordCredential rtCreds = new RTPasswordCredential();

            if (!string.IsNullOrEmpty(creds.UserName))
            {
                if (!string.IsNullOrEmpty(creds.Domain))
                {
                    rtCreds.UserName = creds.Domain + "\\" + creds.UserName;
                }
                else
                {
                    rtCreds.UserName = creds.UserName;
                }
            }
            if (!string.IsNullOrEmpty(creds.Password))
            {
                rtCreds.Password = creds.Password;
            }

            return(rtCreds);
        }
        private Windows.Security.Credentials.PasswordCredential GetCredentialFromLocker()
        {
            try
            {
                Windows.Security.Credentials.PasswordCredential credential = null;

                var vault          = new Windows.Security.Credentials.PasswordVault();
                var credentialList = vault.FindAllByResource(resourceName);
                if (credentialList.Count > 0)
                {
                    if (credentialList.Count == 1)
                    {
                        credential = credentialList[0];
                    }
                }

                return(credential);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
        private RTPasswordCredential RTPasswordCredentialFromNetworkCredential(NetworkCredential creds)
        {
            // RTPasswordCredential doesn't allow assigning string.Empty values, but those are the default values.
            RTPasswordCredential rtCreds = new RTPasswordCredential();

            if (!string.IsNullOrEmpty(creds.UserName))
            {
                if (!string.IsNullOrEmpty(creds.Domain))
                {
                    rtCreds.UserName = string.Format(CultureInfo.InvariantCulture, "{0}\\{1}", creds.Domain, creds.UserName);
                }
                else
                {
                    rtCreds.UserName = creds.UserName;
                }
            }
            if (!string.IsNullOrEmpty(creds.Password))
            {
                rtCreds.Password = creds.Password;
            }

            return(rtCreds);
        }
        private void StoreToken(string token)
        {
            var cred = new Windows.Security.Credentials.PasswordCredential(IdentityManager.AccessControlNamespace, Name, token);

            new Windows.Security.Credentials.PasswordVault().Add(cred);
        }
Beispiel #22
0
        private RTPasswordCredential RTPasswordCredentialFromNetworkCredential(NetworkCredential creds)
        {
            // RTPasswordCredential doesn't allow assigning string.Empty values, but those are the default values.
            RTPasswordCredential rtCreds = new RTPasswordCredential();
            if (!string.IsNullOrEmpty(creds.UserName))
            {
                if (!string.IsNullOrEmpty(creds.Domain))
                {
                    rtCreds.UserName = creds.Domain + "\\" + creds.UserName;
                }
                else
                {
                    rtCreds.UserName = creds.UserName;
                }
            }
            if (!string.IsNullOrEmpty(creds.Password))
            {
                rtCreds.Password = creds.Password;
            }

            return rtCreds;
        }
        private void btnStartAdvertisement_Click(object sender, RoutedEventArgs e)
        {
            _publisher = new WiFiDirectAdvertisementPublisher();
            _publisher.StatusChanged += OnStatusChanged;

            _listener = new WiFiDirectConnectionListener();

            if (chkListener.IsChecked.Value)
            {
                try
                {
                    // This can raise an exception if the machine does not support WiFi. Sorry.
                    _listener.ConnectionRequested += OnConnectionRequested;
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser($"Error preparing Advertisement: {ex}", NotifyType.ErrorMessage);
                    return;
                }
            }

            var discoverability = Utils.GetSelectedItemTag<WiFiDirectAdvertisementListenStateDiscoverability>(cmbListenState);
            _publisher.Advertisement.ListenStateDiscoverability = discoverability;

            _publisher.Advertisement.IsAutonomousGroupOwnerEnabled = chkPreferGroupOwnerMode.IsChecked.Value;

            // Legacy settings are meaningful only if IsAutonomousGroupOwnerEnabled is true.
            if (_publisher.Advertisement.IsAutonomousGroupOwnerEnabled && chkLegacySetting.IsChecked.Value)
            {
                _publisher.Advertisement.LegacySettings.IsEnabled = true;
                if (!String.IsNullOrEmpty(txtPassphrase.Text))
                {
                    var creds = new Windows.Security.Credentials.PasswordCredential();
                    creds.Password = txtPassphrase.Text;
                    _publisher.Advertisement.LegacySettings.Passphrase = creds;
                }

                if (!String.IsNullOrEmpty(txtSsid.Text))
                {
                    _publisher.Advertisement.LegacySettings.Ssid = txtSsid.Text;
                }
            }

            // Add the information elements.
            foreach (WiFiDirectInformationElement informationElement in _informationElements)
            {
                _publisher.Advertisement.InformationElements.Add(informationElement);
            }

            _publisher.Start();

            if (_publisher.Status == WiFiDirectAdvertisementPublisherStatus.Started)
            {
                btnStartAdvertisement.IsEnabled = false;
                btnStopAdvertisement.IsEnabled = true;
                rootPage.NotifyUser("Advertisement started.", NotifyType.StatusMessage);
            }
            else
            {
                rootPage.NotifyUser($"Advertisement failed to start. Status is {_publisher.Status}", NotifyType.ErrorMessage);
            }
        }
 static void DumpCredentials(Windows.Security.Credentials.PasswordCredential cred)
 {
     Console.WriteLine("Resource: {0}", cred.Resource);
     Console.WriteLine("UserName: {0}", cred.UserName);
     Console.WriteLine("Password: {0}", cred.Password);
 }
        private void btnStartAdvertisement_Click(object sender, RoutedEventArgs e)
        {
            _publisher = new WiFiDirectAdvertisementPublisher();
            _publisher.StatusChanged += OnStatusChanged;

            _listener = new WiFiDirectConnectionListener();

            if (chkListener.IsChecked.Value)
            {
                try
                {
                    // This can raise an exception if the machine does not support WiFi. Sorry.
                    _listener.ConnectionRequested += OnConnectionRequested;
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser($"Error preparing Advertisement: {ex}", NotifyType.ErrorMessage);
                    return;
                }
            }

            var discoverability = Utils.GetSelectedItemTag <WiFiDirectAdvertisementListenStateDiscoverability>(cmbListenState);

            _publisher.Advertisement.ListenStateDiscoverability = discoverability;

            _publisher.Advertisement.IsAutonomousGroupOwnerEnabled = chkPreferGroupOwnerMode.IsChecked.Value;

            // Legacy settings are meaningful only if IsAutonomousGroupOwnerEnabled is true.
            if (_publisher.Advertisement.IsAutonomousGroupOwnerEnabled && chkLegacySetting.IsChecked.Value)
            {
                _publisher.Advertisement.LegacySettings.IsEnabled = true;
                if (!String.IsNullOrEmpty(txtPassphrase.Text))
                {
                    var creds = new Windows.Security.Credentials.PasswordCredential();
                    creds.Password = txtPassphrase.Text;
                    _publisher.Advertisement.LegacySettings.Passphrase = creds;
                }

                if (!String.IsNullOrEmpty(txtSsid.Text))
                {
                    _publisher.Advertisement.LegacySettings.Ssid = txtSsid.Text;
                }
            }

            // Add the information elements.
            foreach (WiFiDirectInformationElement informationElement in _informationElements)
            {
                _publisher.Advertisement.InformationElements.Add(informationElement);
            }

            _publisher.Start();

            if (_publisher.Status == WiFiDirectAdvertisementPublisherStatus.Started)
            {
                btnStartAdvertisement.IsEnabled = false;
                btnStopAdvertisement.IsEnabled  = true;
                rootPage.NotifyUser("Advertisement started.", NotifyType.StatusMessage);
            }
            else
            {
                rootPage.NotifyUser($"Advertisement failed to start. Status is {_publisher.Status}", NotifyType.ErrorMessage);
            }
        }
 private void StoreToken(string token)
 {
     var cred = new Windows.Security.Credentials.PasswordCredential(IdentityManager.AccessControlNamespace, Name, token);
     new Windows.Security.Credentials.PasswordVault().Add(cred);
 }
Beispiel #27
0
        public async Task <T> IdentifyAsync <T>(AuthenticationProvider provider, ACSProvider ACSProvider = null) where T : Identity, new()
        {
            var vault = new Windows.Security.Credentials.PasswordVault();

            try
            {
                var tok = vault.Retrieve(AccessControlNamespace, provider.ToString());
                if (IsExpired(tok.Password))
                {
                    vault.Remove(tok);
                }
                else
                {
                    return(new T()
                    {
                        Token = tok.Password, Success = true, Provider = provider
                    });
                }
            }
            catch (Exception ex)
            {
            }


            string LoginUrl      = "";
            string BouncerEndUrl = "";

            switch (provider)
            {
            case AuthenticationProvider.AzureControlService:
                if (ACSProvider != null)
                {
                    LoginUrl = ACSProvider.LoginUrl;
                }
                else
                {
                    if (string.IsNullOrEmpty(AccessControlNamespace))
                    {
                        throw new ArgumentNullException("AccessControlNamespace");
                    }
                    if (string.IsNullOrEmpty(Realm))
                    {
                        throw new ArgumentNullException("Realm");
                    }
                    if (string.IsNullOrEmpty(BouncerReplyUrl))
                    {
                        throw new ArgumentNullException("BouncerReplyUrl");
                    }
                    LoginUrl = string.Format(ACS_Login_Feed,
                                             AccessControlNamespace,
                                             Realm, BouncerReplyUrl);
                }
                BouncerEndUrl = BouncerReplyUrl + "end";
                break;

            case AuthenticationProvider.Facebook:
                LoginUrl = string.Format(Facebook_Login_Feed,
                                         Uri.EscapeDataString(FacebookApplicationID),
                                         Uri.EscapeDataString(Facebook_LoginSucces));
                BouncerEndUrl = Facebook_LoginSucces;
                break;
            }


            return(await WebAuthenticationBroker.AuthenticateAsync(
                       WebAuthenticationOptions.None,
                       new Uri(LoginUrl),
                       new Uri(BouncerEndUrl)).AsTask <WebAuthenticationResult>()
                   .ContinueWith <T>(t =>
            {
                var response = t.Result;
                if (!t.IsFaulted && (response.ResponseStatus == WebAuthenticationStatus.Success))
                {
                    string token = response.ResponseData;                  // response.ResponseData.Substring(response.ResponseData.IndexOf('=') + 1);
                    token = token.Replace(BouncerEndUrl, "").Substring(1); //Assume that the url is the BouncerEndUrl + '#' / '?' + claims.

                    if (provider == AuthenticationProvider.Facebook)
                    {
                        var idx = token.IndexOf("&expires_in=");
                        var time = int.Parse(token.Substring(idx + 12));
                        token = token.Insert(idx, string.Format("&ExpiresOn={0}", (int)DateTime.UtcNow.Add(TimeSpan.FromSeconds(time)).Subtract(Epoch).TotalSeconds));
                    }

                    if (UsePasswordVault)
                    {
                        var cred = new Windows.Security.Credentials.PasswordCredential(AccessControlNamespace,
                                                                                       provider.ToString(), token);
                        new Windows.Security.Credentials.PasswordVault().Add(cred);
                    }
                    return new T()
                    {
                        Token = token, Success = true, Provider = provider
                    };
                }
                else
                {
                    return new T()
                    {
                        UnSuccessReason = response.ResponseStatus.ToString(),
                        Success = false, Provider = provider
                    }
                };
            }));
        }
Beispiel #28
0
        private RTPasswordCredential RTPasswordCredentialFromNetworkCredential(NetworkCredential creds)
        {
            // RTPasswordCredential doesn't allow assigning string.Empty values, but those are the default values.
            RTPasswordCredential rtCreds = new RTPasswordCredential();
            if (!string.IsNullOrEmpty(creds.UserName))
            {
                if (!string.IsNullOrEmpty(creds.Domain))
                {
                    rtCreds.UserName = string.Format(CultureInfo.InvariantCulture, "{0}\\{1}", creds.Domain, creds.UserName);
                }
                else
                {
                    rtCreds.UserName = creds.UserName;
                }
            }
            if (!string.IsNullOrEmpty(creds.Password))
            {
                rtCreds.Password = creds.Password;
            }

            return rtCreds;
        }
Beispiel #29
0
        /// <summary>
        /// Event handler to process WebDAV errors.
        /// If server returns 401 or 302 response here we show the login dialog.
        /// </summary>
        /// <param name="sender">Request to the WebDAV server.</param>
        /// <param name="e">WebDAV error details.</param>
        private static void DavClient_WebDavError(IWebRequestAsync sender, WebDavErrorEventArgs e)
        {
            WebDavHttpException httpException = e.Exception as WebDavHttpException;

            log.Info($"\n{httpException?.Status.Code} {httpException?.Status.Description} {e.Exception.Message} ");
            if (httpException != null)
            {
                switch (httpException.Status.Code)
                {
                // 302 redirect to login page.
                case 302:
                    if (loginRetriesCurrent < loginRetriesMax)
                    {
                        loginRetriesCurrent++;

                        // Show login dialog.

                        // Azure AD can not navigate directly to login page - failed corelation.
                        //string loginUrl = ((Redirect302Exception)e.Exception).Location;
                        //Uri url = new System.Uri(loginUrl, System.UriKind.Absolute);

                        Uri failedUri = (e.Exception as WebDavHttpException).Uri;

                        WebDAVDrive.UI.WebBrowserLogin webBrowserLogin = null;
                        Thread thread = new Thread(() => {
                            webBrowserLogin       = new WebDAVDrive.UI.WebBrowserLogin(failedUri, e.Request, DavClient, log);
                            webBrowserLogin.Title = Settings.ProductName;
                            webBrowserLogin.ShowDialog();
                        });
                        thread.SetApartmentState(ApartmentState.STA);
                        thread.Start();
                        thread.Join();

                        /*
                         * if (loginForm.Cookies != null)
                         * {
                         *  // Attach cookies to all future requests.
                         *  DavClient.CookieContainer.Add(loginForm.Cookies);
                         *  e.Result = WebDavErrorEventResult.Fail;
                         *
                         *  // Set successful response and continue processing.
                         *  e.Response = loginForm.Response;
                         *  e.Result = WebDavErrorEventResult.ContinueProcessing;
                         *
                         *  // Alternatively you can modify this request, attaching cookies or headers, and replay it.
                         *  //e.Request.CookieContainer.Add(loginForm.Cookies);
                         *  //e.Result = WebDavErrorEventResult.Repeat;
                         * }
                         */
                    }
                    break;

                // Challenge-responce auth: Basic, Digest, NTLM or Kerberos
                case 401:
                    if (loginRetriesCurrent < loginRetriesMax)
                    {
                        Uri failedUri = (e.Exception as WebDavHttpException).Uri;
                        Windows.Security.Credentials.PasswordCredential passwordCredential = CredentialManager.GetCredentials(Settings.ProductName, log);
                        if (passwordCredential != null)
                        {
                            passwordCredential.RetrievePassword();
                            DavClient.Credentials = new NetworkCredential(passwordCredential.UserName, passwordCredential.Password);
                        }
                        else
                        {
                            string       login        = null;
                            SecureString password     = null;
                            bool         dialogResult = false;
                            bool         keepLogedin  = false;

                            // Show login dialog
                            WebDAVDrive.UI.ChallengeLogin loginForm = null;
                            Thread thread = new Thread(() =>
                            {
                                loginForm = new WebDAVDrive.UI.ChallengeLogin();
                                ((ChallengeLoginViewModel)loginForm.DataContext).Url         = failedUri.OriginalString;
                                ((ChallengeLoginViewModel)loginForm.DataContext).WindowTitle = Settings.ProductName;
                                loginForm.ShowDialog();

                                login        = ((ChallengeLoginViewModel)loginForm.DataContext).Login;
                                password     = ((ChallengeLoginViewModel)loginForm.DataContext).Password;
                                keepLogedin  = ((ChallengeLoginViewModel)loginForm.DataContext).KeepLogedIn;
                                dialogResult = (bool)loginForm.DialogResult;
                            });
                            thread.SetApartmentState(ApartmentState.STA);
                            thread.Start();
                            thread.Join();

                            loginRetriesCurrent++;
                            if (dialogResult)
                            {
                                if (keepLogedin)
                                {
                                    CredentialManager.SaveCredentials(Settings.ProductName, login, password);
                                }
                                DavClient.Credentials = new NetworkCredential(login, password);
                            }
                        }
                    }
                    break;
                }
            }
        }