Пример #1
0
 private async void EmailProtectionSwitch_Toggled(object sender, RoutedEventArgs e)
 {
     if (EmailProtectionSwitch.IsOn)
     {
         if (await KeyCredentialManager.IsSupportedAsync())
         {
             ApplicationData.Current.LocalSettings.Values["EmailProtectionMode"] = true;
         }
         else
         {
             EmailProtectionSwitch.IsOn = false;
             ApplicationData.Current.LocalSettings.Values["EmailProtectionMode"] = false;
             ContentDialog dialog = new ContentDialog
             {
                 Title             = "警告",
                 Content           = "    由于Windows Hello尚未设置,无法启用Windows Hello验证\r\r    请先设置Windows Hello后再试",
                 PrimaryButtonText = "前往",
                 CloseButtonText   = "取消",
                 Background        = Application.Current.Resources["DialogAcrylicBrush"] as Brush
             };
             dialog.PrimaryButtonClick += async(s, t) =>
             {
                 await Launcher.LaunchUriAsync(new Uri("ms-settings:signinoptions"));
             };
             _ = await dialog.ShowAsync();
         }
     }
     else
     {
         ApplicationData.Current.LocalSettings.Values["EmailProtectionMode"] = false;
     }
 }
Пример #2
0
        private async void SignInWithPassword()
        {
            // Perform traditional standard authentication here.
            // Our sample accepts any userid and password.

            // Next, see if we can offer to switch to Windows Hello sign-in.
            // Check if the device is capable of provisioning Microsoft Passport key credentials and
            // the user has set up Windows Hello with a PIN on the device.
            if (await KeyCredentialManager.IsSupportedAsync())
            {
                // Navigate to Enable Hello Page, passing the account ID (username) as a parameter
                string accountID = UserNameTextBox.Text;
                Frame.Navigate(typeof(EnableHelloPage), accountID);
            }
            else
            {
                // Windows Hello is not available, so go directly to the signed-in state.
                // For the purpose of this sample, we will display a message to indicate
                // that this code path has been reached.
                MessageDialog message = new MessageDialog("Sample note: Windows Hello is not set up");
                await message.ShowAsync();

                return;
            }
        }
Пример #3
0
        public static async Task <bool> Login()
        {
            var result = await KeyCredentialManager.IsSupportedAsync();

            String message;

            if (result)
            {
                var authenticationResult = await KeyCredentialManager.RequestCreateAsync("login", KeyCredentialCreationOption.ReplaceExisting);

                if (authenticationResult.Status == KeyCredentialStatus.Success)
                {
                    message = "User is logged in";
                }
                else
                {
                    message = "Login error: " + authenticationResult.Status;
                }
            }
            else
            {
                message = "Windows Hello is not enabled for this device.";
            }

            String imagePath = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
            String xml       = "<toast><visual><binding template='ToastGeneric'><text hint-maxLines='1'>" + message + "</text></binding></visual></toast>";

            Toast.CreateToast(xml);

            return(result);
        }
Пример #4
0
        /// <summary>
        /// Decrypts the user's profile and logs in
        /// </summary>
        /// <returns></returns>
        private async Task EnterProfile(ProfileModel profile, string passphrase)
        {
            try
            {
                // Check the profile and determine if the passphrase is correct
                await KryptPadApi.LoadProfileAsync(profile.Profile, passphrase);


                // Success, tell the app we are signed in
                (App.Current as App).SignInStatus = SignInStatus.SignedInWithProfile;

                // Check if Windows hellow is supported and save the passphrase
                var supported = await KeyCredentialManager.IsSupportedAsync();

                if (supported && SavePassphraseEnabled)
                {
                    // Prompt to save profile passphrase if Windows Hello is enabled
                    StorePassphrase(profile.Id.ToString(), passphrase);
                }

                // When a profile is selected, navigate to main page
                NavigationHelper.Navigate(typeof(ItemsPage), null, NavigationHelper.NavigationType.Main);
            }
            catch (WebException)
            {
                // Something went wrong in the api
                await DialogHelper.ShowMessageDialogAsync(ResourceHelper.GetString("UnlockProfileFailed"));
            }
            catch (Exception ex)
            {
                // Failed
                await DialogHelper.ShowGenericErrorDialogAsync(ex);
            }
        }
Пример #5
0
        static async Task <(int err, byte[] sig)> VerifyUser(string key_name, string contentToSign)
        {
            if (await KeyCredentialManager.IsSupportedAsync() == false)
            {
                await(new MessageDialog("KeyCredentialManager not supported")).ShowAsync();
                return(ERR_VERIFY_HELLO_NOT_SUPPORTED, null);
            }

            var key = await KeyCredentialManager.OpenAsync(key_name);

            if (key.Status != KeyCredentialStatus.Success)
            {
                return(CredentialStatusToExitCode(key.Status), null);
            }

            var buf     = CryptographicBuffer.ConvertStringToBinary(contentToSign, BinaryStringEncoding.Utf8);
            var signRes = await key.Credential.RequestSignAsync(buf);

            if (signRes.Status != KeyCredentialStatus.Success)
            {
                return(CredentialStatusToExitCode(key.Status), null);
            }

            byte[] sig;
            CryptographicBuffer.CopyToByteArray(signRes.Result, out sig);
            return(0, sig);
        }
Пример #6
0
        public async ValueTask <bool> IsSupportedAsync()
        {
            // https://docs.microsoft.com/zh-cn/windows/uwp/security/microsoft-passport#3-implementing-windows-hello
            var keyCredentialAvailable = await KeyCredentialManager.IsSupportedAsync();

            return(keyCredentialAvailable);
        }
        private async void Hello_Click(object sender, RoutedEventArgs e)
        {
            var keyCredentialAvailable = await KeyCredentialManager.IsSupportedAsync();

            var result = await KeyCredentialManager.RequestCreateAsync(Viewmodel.Username, KeyCredentialCreationOption.ReplaceExisting);

            //return public key, Attestation and Username to ASB for backend storage. Visit: https://docs.microsoft.com/en-us/windows/uwp/security/microsoft-passport for more info
            Result.TrySetResult(true);
        }
Пример #8
0
        public static async Task <bool> MicrosoftPassportAvailableCheckasync()
        {
            bool keyCredentialAvailable = await KeyCredentialManager.IsSupportedAsync();

            if (keyCredentialAvailable == false)
            {
                Debug.WriteLine("device is not setup go to setting and setup");
            }
            return(false);
        }
Пример #9
0
        public static async Task <bool> MicrosoftPassportAvailableCheckAsync()
        {
            bool keyCredentialAvailable = await KeyCredentialManager.IsSupportedAsync();

            if (keyCredentialAvailable == false)
            {
                Debug.WriteLine("Microsoft Passport is not setup!\nPlease go to Windows Settings and set up a PIN to use it.");
                return(false);
            }
            return(true);
        }
Пример #10
0
 private async void button1_ClickAsync(object sender, EventArgs e)
 {
     userId = UserName.Text;
     if (await KeyCredentialManager.IsSupportedAsync())
     {
         // Navigate to Enable Hello Page, passing the account ID (username) as a parameter
         MessageBox.Show("Support Windows Hello");
         await StartUsingWindowsHello();
     }
     else
     {
     }
 }
Пример #11
0
        public static async Task <bool> testPassportAvailable()
        {
            bool x = await KeyCredentialManager.IsSupportedAsync();

            if (x == true)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        /// <summary>
        /// Checks to see if Passport is ready to be used.
        ///
        /// Passport has dependencies on:
        ///     1. Having a connected Microsoft Account
        ///     2. Having a Windows PIN set up for that _account on the local machine
        /// </summary>
        public static async Task <bool> WindowsHelloAvailableCheckAsync()
        {
            bool keyCredentialAvailable = await KeyCredentialManager.IsSupportedAsync();

            if (keyCredentialAvailable == false)
            {
                // Key credential is not enabled yet as user
                // needs to connect to a Microsoft Account and select a PIN in the connecting flow.
                Debug.WriteLine("Microsoft Passport is not setup!\nPlease go to Windows Settings and set up a PIN to use it.");
                return(false);
            }

            return(true);
        }
Пример #13
0
 public async Task TrySetupWindowsHelloAsync(string userName)
 {
     if (await KeyCredentialManager.IsSupportedAsync())
     {
         if (await DialogService.ShowAsync("Windows Hello", "Your device supports Windows Hello and you can use it to authenticate with the app.\r\n\r\nDo you want to enable Windows Hello for your next sign in with this user?", "Ok", "Maybe later"))
         {
             await SetupWindowsHelloAsync(userName);
         }
         else
         {
             await TryDeleteCredentialAccountAsync(userName);
         }
     }
 }
Пример #14
0
        public async void RefreshHelloSecurity()
        {
            var HelloAvailable = await KeyCredentialManager.IsSupportedAsync();

            if (HelloAvailable)
            {
                SettingsPartViewModel.EnableHelloSecurity = Visibility.Collapsed;
            }
            else
            {
                SettingsPartViewModel.UseHelloSecurity    = false;
                SettingsPartViewModel.EnableHelloSecurity = Visibility.Visible;
            }
        }
Пример #15
0
        public static async Task <bool> MicrosoftPassportAvailableCheckAsync()
        {
            bool keyCredentialAvailable = await KeyCredentialManager.IsSupportedAsync();

            if (keyCredentialAvailable == false)
            {
                // Key credential is not enabled yet as user
                // needs to connect to a Microsoft Account and select a PIN in the connecting flow.
                var messageDialog = new MessageDialog("You need to login with your account before use this functionality.");
                await messageDialog.ShowAsync();

                return(false);
            }

            return(true);
        }
Пример #16
0
        /// <summary>
        /// Checks to see if Passport is ready to be used.
        ///
        /// Passport has dependencies on:
        ///     1. Having a connected MSA Account
        ///     2. Having a Windows PIN set up for that account on the local machine
        ///
        /// If Passport is not ready, then display how to set it up to the user and
        /// disable the "Sign In with Passport" button.
        /// </summary>
        private async void PassportAvailableCheck()
        {
            var keyCredentialAvailable = await KeyCredentialManager.IsSupportedAsync();

            if (keyCredentialAvailable == false)
            {
                //
                // Key credential is not enabled yet as user
                // needs to connect to a MSA account and select a pin in the connecting flow.
                //
                grid_PassportStatus.Background    = new SolidColorBrush(Color.FromArgb(255, 50, 170, 207));
                textblock_PassportStatusText.Text = "Microsoft Passport is not set up.\nPlease go to Windows Settings and connect an MSA account!";
                button_PassportSignIn.IsEnabled   = false;
                m_passportAvailable = false;
            }
        }
        /// <summary>
        ///     Authenticate the user using biometrics.
        /// </summary>
        /// <param name="ct">The <see cref="CancellationToken" /> to use.</param>
        /// <returns>A <see cref="BiometryResult" /> enum value.</returns>
        public async Task <BiometryResult> ValidateIdentity(CancellationToken ct)
        {
            if (this.Log().IsEnabled(LogLevel.Debug))
            {
                this.Log().Debug("Authenticating the fingerprint.");
            }

            await KeyCredentialManager.IsSupportedAsync();

            if (this.Log().IsEnabled(LogLevel.Information))
            {
                this.Log().Info("Successfully authenticated the fingerprint.");
            }

            return(new BiometryResult());
        }
Пример #18
0
        /// <summary>
        /// Checks and starts Windows Hello login, if possible and desired
        /// </summary>
        public async void CheckCapabilityWindowsHello()
        {
            if (await KeyCredentialManager.IsSupportedAsync())
            {
                WindowsHelloIsUsable = true;
                var settings = SettingsService.Instance;
                if (settings.PreferWindowsHello == Services.Enums.WindowsHelloPreferEnum.None)
                {
                    var dialog   = new ContentDialog();
                    var markdown = new MarkdownTextBlock
                    {
                        Text = Resources.WindowsHelloPreferMessage
                    };
                    dialog.Content             = markdown;
                    dialog.PrimaryButtonText   = Resources.Yes;
                    dialog.SecondaryButtonText = Resources.No;
                    var result = await _dialogService.ShowAsync(dialog);

                    switch (result)
                    {
                    case ContentDialogResult.None:
                        break;

                    case ContentDialogResult.Primary:
                        settings.PreferWindowsHello = Services.Enums.WindowsHelloPreferEnum.Prefer;
                        WindowsHelloLogin();
                        break;

                    case ContentDialogResult.Secondary:
                        settings.PreferWindowsHello = Services.Enums.WindowsHelloPreferEnum.No;
                        break;

                    default:
                        break;
                    }
                }
                else if (settings.PreferWindowsHello == Services.Enums.WindowsHelloPreferEnum.Prefer)
                {
                    if (!IsLogout)
                    {
                        WindowsHelloLogin();
                    }
                }
            }
        }
Пример #19
0
        /// <summary>
        /// Function called when regular username/password sign in button is clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Button_SignIn_Click(object sender, RoutedEventArgs e)
        {
            if (this.textbox_Username.Text == string.Empty || this.passwordbox_Password.Password == string.Empty)
            {
                this.textblock_ErrorField.Visibility = Visibility.Visible;
                return;
            }
            else
            {
                this.textblock_ErrorField.Visibility = Visibility.Collapsed;
            }
            bool isNewAccount = false;

            if (this.m_account == null)
            {
                this.m_account = new Account()
                {
                    head = "Assets/head.png", Name = this.textbox_Username.Text, Email = this.textbox_Username.Text, loginCount = 0, UsesPassport = false, isAdd = false
                };
                isNewAccount = true;
            }
            LoginHelp loginHelp = new LoginHelp(this.m_account);
            bool      rev       = await loginHelp.SignInPassword(isNewAccount);

            if (rev)
            {
                //Checks to see if Passport is ready to be used.
                //1. Having a connected MSA Account
                //2. Having a Windows PIN set up for that account on the local machine
                var keyCredentialAvailable = await KeyCredentialManager.IsSupportedAsync();

                if (!this.m_account.UsesPassport && keyCredentialAvailable)
                {
                    this.Frame.Navigate(typeof(SelecteHello), this.m_account);
                    return;
                }
                this.Frame.Navigate(typeof(AccountDetails), this.m_account);
            }
            else
            {
                rootPage.ShowMessage("SignIn Failure");
            }
        }
Пример #20
0
        public async void Load()
        {
            try
            {
                if (await KeyCredentialManager.IsSupportedAsync())
                {
                    var result = await KeyCredentialManager.OpenAsync(Helper.AppName);

                    if (result.Credential != null)
                    {
                        var signResult = await result.Credential.RequestSignAsync(CryptographicBuffer.ConvertStringToBinary(DeviceHelper.PackageName, BinaryStringEncoding.Utf8));

                        if (signResult.Status == KeyCredentialStatus.Success)
                        {
                            Unlock();
                        }
                        else
                        {
                            BiometricsButton.Visibility = Visibility.Visible;
                        }
                    }
                    else
                    {
                        var creationResult = await KeyCredentialManager.RequestCreateAsync(Helper.AppName, KeyCredentialCreationOption.ReplaceExisting);

                        if (creationResult.Status == KeyCredentialStatus.Success)
                        {
                            Unlock();
                        }
                        else
                        {
                            BiometricsButton.Visibility = Visibility.Visible;
                        }
                    }
                }
                else
                {
                    PassText.Focus(FocusState.Keyboard);
                }
            }
            catch { }
        }
Пример #21
0
        private async void BiometricsButtonClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (await KeyCredentialManager.IsSupportedAsync())
                {
                    var creationResult = await KeyCredentialManager.RequestCreateAsync(Helper.AppName, KeyCredentialCreationOption.ReplaceExisting);

                    if (creationResult.Status == KeyCredentialStatus.Success)
                    {
                        Unlock();
                    }
                    else
                    {
                        BiometricsButton.Visibility = Visibility.Visible;
                    }
                }
            }
            catch { }
        }
Пример #22
0
        /// <summary>
        /// Method which occurs when the page is laid out, rendered, and ready for interaction.
        /// Loads app settings state and checks if Windows Hello is available in the system.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            UseWindowsHelloCheckBox.IsChecked = ApplicationData.Current.LocalSettings.Values.ContainsKey("HelloAuthenticationEnabled");

            if (!await KeyCredentialManager.IsSupportedAsync())
            {
                UseWindowsHelloCheckBox.IsEnabled = false;
                WindowsHelloGrid.Visibility       = Visibility.Visible;
            }
            else
            {
                WindowsHelloGrid.Visibility = Visibility.Collapsed;
            }

            DeviceInformationCollection batteryCollection = await DeviceInformation.FindAllAsync(Battery.GetDeviceSelector());

            BatterySaverGrid.Visibility = batteryCollection.Count > 0 ? Visibility.Visible : Visibility.Collapsed;

            SendDiagnosticDataCheckBox.IsChecked = !ApplicationData.Current.LocalSettings.Values.ContainsKey("AnalyticsDisabled");
        }
Пример #23
0
        private async void ProfileSelectedCommandHandler(object obj)
        {
            var profile = obj as ProfileModel;
            // Get whether credential manager is supported
            var credentialManagerSupported = await KeyCredentialManager.IsSupportedAsync();

            // If Windows Hello is enabled, ask for verification of consent
            if (profile != null &&
                credentialManagerSupported &&
                SavePassphraseEnabled &&
                HasSavedPassphrase(new PasswordVault(), profile?.Id.ToString()))
            {
                // Introduce windows hello
                await PromptForConsent(profile);
            }
            else
            {
                // Prompt the user for the passphrase
                await PromptForPassphrase(profile);
            }
        }
Пример #24
0
        private async void OnLoaded(object sender, RoutedEventArgs e)
        {
            Window.Current.Activated   += Window_Activated;
            Window.Current.SizeChanged += Window_SizeChanged;

            UpdateView();

            if (_passcodeService.IsBiometricsEnabled && await KeyCredentialManager.IsSupportedAsync())
            {
                Biometrics.Visibility = Visibility.Visible;

                if (_biometrics)
                {
                    Biometrics_Click(null, null);
                }
            }
            else
            {
                Field.Focus(FocusState.Keyboard);
                CoreInputView.GetForCurrentView().TryShow();
            }
        }
Пример #25
0
        public async Task Initialise()
        {
            PassportStatus.Text     = "Checking Microsoft Passport state...";
            PassportLoader.IsActive = true;

            await Task.Run(async() =>
            {
                KeyCredentialAvailable = await KeyCredentialManager.IsSupportedAsync();

                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    PassportLoader.IsActive = false;
                    if (!KeyCredentialAvailable)
                    {
                        ContainerPanel.Background = new SolidColorBrush(Color.FromArgb(255, 50, 170, 207));
                        PassportStatus.Text       = "Microsoft Passport is not set up!\nGo to Windows Settings to enable it.";
                        return;
                    }

                    PassportStatus.Text = "Microsoft Passport is ready to use.";
                });
            }).ConfigureAwait(false);
        }
        private static async Task <bool> AuthenticateUsingWindowsHello()
        {
            if (await KeyCredentialManager.IsSupportedAsync())
            {
                // Get credentials for current user and app
                var result = await KeyCredentialManager.OpenAsync("GitIt-Hello");

                if (result.Credential != null)
                {
                    var signResult =
                        await result.Credential.RequestSignAsync(CryptographicBuffer.ConvertStringToBinary("LoginAuth",
                                                                                                           BinaryStringEncoding.Utf8));

                    return(signResult.Status == KeyCredentialStatus.Success);
                }

                // If no credentials found create one
                var creationResult = await KeyCredentialManager.RequestCreateAsync("GitIt-Hello",
                                                                                   KeyCredentialCreationOption.ReplaceExisting);

                return(creationResult.Status == KeyCredentialStatus.Success);
            }
            return(false);
        }
Пример #27
0
        private async Task <PasswordInfoModel> GetPasswordInfoModelAsync()
        {
            PasswordInfoModel model = null;
            var pwInfoFile          = await _storageService.GetCachedTextFileAsync(FileName);

            if (pwInfoFile != null)
            {
                model = JsonConvert.DeserializeObject <PasswordInfoModel>(pwInfoFile);
            }

            if (model == null)
            {
                if (!await KeyCredentialManager.IsSupportedAsync())
                {
                    return(null);
                }

                model = new PasswordInfoModel
                {
                    KeyPhrase = "sign this keyphrase of this bookmarked application to get a secure string"
                };
                var keyCreationResult =
                    await KeyCredentialManager.RequestCreateAsync(AccountId, KeyCredentialCreationOption.ReplaceExisting);

                if (keyCreationResult.Status == KeyCredentialStatus.Success)
                {
                    model.PreferPassword = false;
                }
                else if (keyCreationResult.Status == KeyCredentialStatus.UserPrefersPassword)
                {
                    model.PreferPassword = true;
                }
                await _storageService.SetCachedTextFileAsync(FileName, JsonConvert.SerializeObject(model));
            }
            return(model);
        }
Пример #28
0
        /// <summary>
        /// Checks if Windows Hello is supported and enabled the checkbox
        /// </summary>
        /// <returns></returns>
        public async Task CheckIfWindowsHelloSupported()
        {
            var supported = await KeyCredentialManager.IsSupportedAsync();

            // Enable or disable the checkbox
            WindowsHelloVisibility = supported ? Visibility.Visible : Visibility.Collapsed;

            // Look up saved settings for option
            var roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;

            // Read setting
            var settingValue = roamingSettings.Values["SavePassphraseEnabled"];

            if (settingValue != null)
            {
                // Override checkbox checked value
                SavePassphraseEnabled = (bool)settingValue;
            }
            else if (supported)
            {
                // Preselect the checkbox
                SavePassphraseEnabled = true;
            }
        }
Пример #29
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            user = DataSource.GetInstance().GetUser();
            var passportSetup = await KeyCredentialManager.IsSupportedAsync();

            if (user != null)
            {
                textbox_Username.Text      = user.Email;
                textbox_Username.IsEnabled = false;
                m_addingAccount            = false;

                // check if Hello is available on this machine
                // if not, needs to enable it in Windows Settings
                if (passportSetup && user.UsesPassport)
                {
                    SignInPassport(true);
                }
            }

            if (!passportSetup)
            {
                button_PassportSignIn.Visibility = Visibility.Collapsed;
            }
        }
Пример #30
0
        public Shell()
        {
            InitializeComponent();

            Instance = this;

            HamMen = new HamburgerMenu();

            if (StoreServicesFeedbackLauncher.IsSupported())
            {
                FeedbackButton.Visibility = Visibility.Visible;
            }

            CustomSettings.UserLogChanged -= CustomSettings_IsUserLoggedChanged;
            CustomSettings.UserLogChanged += CustomSettings_IsUserLoggedChanged;

            CustomSettings.ShowAdsChanged -= CustomSettings_ShowAdsChanged;
            CustomSettings.ShowAdsChanged += CustomSettings_ShowAdsChanged;

            SettingsPartViewModel.HelloSecurityChanged -= SettingsPartViewModel_HelloSecurityChanged;
            SettingsPartViewModel.HelloSecurityChanged += SettingsPartViewModel_HelloSecurityChanged;

            AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested -= BuildLoginPaneAsync;
            AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested += BuildLoginPaneAsync;

            CoreApplicationViewTitleBar titleBar = CoreApplication.GetCurrentView().TitleBar;

            titleBar.LayoutMetricsChanged -= TitleBar_LayoutMetricsChanged;
            titleBar.LayoutMetricsChanged += TitleBar_LayoutMetricsChanged;

            LoggingButton.IsEnabled = SettingsService.Instance.UseHelloSecurity && KeyCredentialManager.IsSupportedAsync().AsTask().Result;

            uiSettings.ColorValuesChanged += ThemeChanger;

            NavView.ShowAd = Visibility.Collapsed;
        }