/// <summary>
        /// 请求注册用户
        /// </summary>
        /// <returns></returns>
        public static async Task <AuthenticatorState> RegisterUserAsync()
        {
            if (await CheckSupportAsync().ConfigureAwait(false))
            {
                KeyCredentialRetrievalResult CredentiaResult = await KeyCredentialManager.RequestCreateAsync(CredentialName, KeyCredentialCreationOption.ReplaceExisting);

                switch (CredentiaResult.Status)
                {
                case KeyCredentialStatus.Success:
                {
                    string PublicKey = CryptographicBuffer.EncodeToHexString(CredentiaResult.Credential.RetrievePublicKey());
                    ApplicationData.Current.LocalSettings.Values["WindowsHelloPublicKeyForUser"] = PublicKey;
                    return(AuthenticatorState.RegisterSuccess);
                }

                case KeyCredentialStatus.UserCanceled:
                {
                    return(AuthenticatorState.UserCanceled);
                }

                default:
                {
                    return(AuthenticatorState.UnknownError);
                }
                }
            }
            else
            {
                return(AuthenticatorState.WindowsHelloUnsupport);
            }
        }
Пример #2
0
 public AccountController(AppUserManager userManager, KeyCredentialManager keyManager, AppIdentityDbContext context, FidoMetadataService metadataService, ILogger <AccountController> logger)
 {
     _userManager     = userManager;
     _keyManager      = keyManager;
     _metadataService = metadataService;
     _logger          = logger;
 }
Пример #3
0
        private async Task <IBuffer> CreatePassportKeyCredentialAsync()
        {
            // Create a new KeyCredential for the user on the device.
            KeyCredentialRetrievalResult keyCreationResult = await KeyCredentialManager.RequestCreateAsync(userId, KeyCredentialCreationOption.ReplaceExisting);

            if (keyCreationResult.Status == KeyCredentialStatus.Success)
            {
                // User has autheniticated with Windows Hello and the key credential is created.
                KeyCredential userKey = keyCreationResult.Credential;
                return(userKey.RetrievePublicKey());
            }
            else if (keyCreationResult.Status == KeyCredentialStatus.NotFound)
            {
                MessageDialog message = new MessageDialog("To proceed, Windows Hello needs to be configured in Windows Settings (Accounts -> Sign-in options)");
                await message.ShowAsync();

                return(null);
            }
            else if (keyCreationResult.Status == KeyCredentialStatus.UnknownError)
            {
                MessageDialog message = new MessageDialog("The key credential could not be created. Please try again.");
                await message.ShowAsync();

                return(null);
            }

            return(null);
        }
Пример #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
Файл: Util.cs Проект: ice0/test
        public static async Task <bool> TryDeleteCredentialAccountAsync(string userId)
        {
            bool deleted = false;

            try
            {
                await KeyCredentialManager.DeleteAsync(userId);

                deleted = true;
            }
            catch (Exception ex)
            {
                switch (ex.HResult)
                {
                case NTE_NO_KEY:
                    // Key is already deleted. Ignore this error.
                    break;

                case NTE_PERM:
                    // Access is denied. Ignore this error. We tried our best.
                    break;

                default:
                    throw;
                }
            }
            return(deleted);
        }
Пример #6
0
        public static async Task <bool> UnlinkAccount(string userId)
        {
            var retrieveResult = await KeyCredentialManager.OpenAsync(userId);

            if (retrieveResult.Status != KeyCredentialStatus.Success)
            {
                return(false);
            }

            KeyCredential userCredential = retrieveResult.Credential;

            string publicKeyHint = CalculatePublicKeyHint(userCredential.RetrievePublicKey());

            var unlinkResult = await PlayFab.PlayFabClientAPI.UnlinkWindowsHelloAsync(new UnlinkWindowsHelloAccountRequest
            {
                PublicKeyHint = publicKeyHint
            });

            if (unlinkResult.Error != null)
            {
                MessageDialog message = new MessageDialog($"Error while un-linking: {unlinkResult.Error.Error} {unlinkResult.Error.ErrorMessage}");
                await message.ShowAsync();
            }

            return(unlinkResult.Error == null);
        }
Пример #7
0
        /// <summary>
        /// Check if a ms passport account exists
        /// </summary>
        /// <exception cref="UserCancelledException"></exception>
        /// <exception cref="UserPrefersPasswordException"></exception>
        /// <exception cref="UnknownException"></exception>
        /// <exception cref="AggregateException"></exception>
        /// <param name="accountId">The id of the account to check</param>
        /// <returns>true if the account exists</returns>
        public static bool PassportAccountExists(string accountId)
        {
            // Try to get the account
            Task <KeyCredentialRetrievalResult> task = Task.Run(async() => await KeyCredentialManager.OpenAsync(accountId));

            // Check the result
            switch (task.Result.Status)
            {
            case KeyCredentialStatus.Success:
                // The account was found
                return(true);

            case KeyCredentialStatus.NotFound:
                // The account was not found
                return(false);

            case KeyCredentialStatus.UserCanceled:
                // The operation was cancelled by the user
                throw new UserCancelledException();

            case KeyCredentialStatus.UserPrefersPassword:
                // The user prefers a password
                throw new UserPrefersPasswordException();

            default:
                // An unknwon error occurred
                throw new UnknownException();
            }
        }
Пример #8
0
        /// <summary>
        /// Creates a Passport key on the machine using the _account id passed.
        /// </summary>
        /// <param name="accountId">The _account id associated with the _account that we are enrolling into Passport</param>
        /// <returns>Boolean representing if creating the Passport key succeeded</returns>
        public static async Task <bool> CreatePassportKeyAsync(string accountId)
        {
            KeyCredentialRetrievalResult keyCreationResult = await KeyCredentialManager.RequestCreateAsync(accountId, KeyCredentialCreationOption.ReplaceExisting);

            switch (keyCreationResult.Status)
            {
            case KeyCredentialStatus.Success:
                // In the real world authentication would take place on a server.
                // So every time a user migrates or creates a new Microsoft Passport account Passport details should be pushed to the server.
                // The details that would be pushed to the server include:
                // The public key, keyAttesation if available,
                // certificate chain for attestation endorsement key if available,
                // status code of key attestation result: keyAttestationIncluded or
                // keyAttestationCanBeRetrievedLater and keyAttestationRetryType
                // As this sample has no concept of a server it will be skipped for now
                // for information on how to do this refer to the second Passport sample

                //For this sample just return true
                return(true);

            case KeyCredentialStatus.UserCanceled:
                //Debug.WriteLine("User cancelled sign-in process.");
                break;

            case KeyCredentialStatus.NotFound:
                // User needs to setup Microsoft Passport
                //Debug.WriteLine("Microsoft Passport is not setup!\nPlease go to Windows Settings and set up a PIN to use it.");
                break;

            default:
                break;
            }

            return(false);
        }
Пример #9
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);
        }
Пример #10
0
        private async void tryToCloseWinHello()
        {
            KeyCredentialRetrievalResult keyCreationResult = await KeyCredentialManager.RequestCreateAsync("WinHello", KeyCredentialCreationOption.ReplaceExisting);

            var resourceLoader = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();

            if (keyCreationResult.Status == KeyCredentialStatus.Success)
            {
                Password.winHelloStatus = false;
                LockButton.IsEnabled    = false;
                Password.WriteWinHelloData();
            }
            else if (keyCreationResult.Status == KeyCredentialStatus.NotFound)
            {
                Password.winHelloStatus = true;
                WHToggle.IsOn           = true;
                MessageDialog message = new MessageDialog(resourceLoader.GetString("WHError1"));
                await message.ShowAsync();
            }
            else if (keyCreationResult.Status == KeyCredentialStatus.UnknownError)
            {
                Password.winHelloStatus = true;
                WHToggle.IsOn           = true;
                MessageDialog message = new MessageDialog(resourceLoader.GetString("WHError2"));
                await message.ShowAsync();
            }
            else
            {
                Password.winHelloStatus = true;
                WHToggle.IsOn           = true;
            }
        }
Пример #11
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);
        }
Пример #12
0
        static private async Task <bool> TryDeleteCredentialAccountAsync(string userName)
        {
            try
            {
                AppSettings.Current.WindowsHelloPublicKeyHint = null;
                await KeyCredentialManager.DeleteAsync(userName);

                return(true);
            }
            catch (Exception ex)
            {
                switch (ex.HResult)
                {
                case NTE_NO_KEY:
                    // Key is already deleted. Ignore this error.
                    break;

                case NTE_PERM:
                    // Access is denied. Ignore this error. We tried our best.
                    break;

                default:
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    break;
                }
            }
            return(false);
        }
Пример #13
0
        public static async Task <bool> CreatePassportKeyAsync(Guid userId, string username)
        {
            KeyCredentialRetrievalResult keyCreationResult = await KeyCredentialManager.RequestCreateAsync(username, KeyCredentialCreationOption.ReplaceExisting);

            switch (keyCreationResult.Status)
            {
            case KeyCredentialStatus.Success:
                Debug.WriteLine("Successfully made key");
                await GetKeyAttestationAsync(userId, keyCreationResult);

                return(true);

            case KeyCredentialStatus.UserCanceled:
                Debug.WriteLine("User cancelled sign-in process.");
                break;

            case KeyCredentialStatus.NotFound:
                // User needs to setup Windows Hello
                Debug.WriteLine("Windows Hello is not setup!\nPlease go to Windows Settings and set up a PIN to use it.");
                break;

            default:
                break;
            }

            return(false);
        }
Пример #14
0
        public const int ERR_CREAT_KEY_EXISTS = 170; // Avoid reserved exit codes of UNIX

        static async Task <(int err, string pubKey)> CreatePublicKey(string key_name)
        {
            int err;
            var createRes = await KeyCredentialManager.RequestCreateAsync(key_name, KeyCredentialCreationOption.FailIfExists);

            IBuffer pubKey;

            if (createRes.Status == KeyCredentialStatus.CredentialAlreadyExists)
            {
                var existing = await KeyCredentialManager.OpenAsync(key_name);

                if (existing.Status != KeyCredentialStatus.Success)
                {
                    return(ERR_CREAT_FAIL, null);
                }
                err    = ERR_CREAT_KEY_EXISTS;
                pubKey = existing.Credential.RetrievePublicKey();
            }
            else if (createRes.Status != KeyCredentialStatus.Success)
            {
                return(ERR_CREAT_FAIL, null);
            }
            else
            {
                err    = 0;
                pubKey = createRes.Credential.RetrievePublicKey();
            }
            var pem = String.Format("-----BEGIN PUBLIC KEY-----\n{0}\n-----END PUBLIC KEY-----\n", CryptographicBuffer.EncodeToBase64String(pubKey));

            return(err, pem);
        }
Пример #15
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);
        }
Пример #16
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;
     }
 }
Пример #17
0
        public async Task <Result> SignInWithWindowsHelloAsync()
        {
            string userName = AppSettings.Current.UserName;

            if (IsWindowsHelloEnabled(userName))
            {
                var retrieveResult = await KeyCredentialManager.OpenAsync(userName);

                if (retrieveResult.Status == KeyCredentialStatus.Success)
                {
                    var credential      = retrieveResult.Credential;
                    var challengeBuffer = CryptographicBuffer.DecodeFromBase64String("challenge");
                    var result          = await credential.RequestSignAsync(challengeBuffer);

                    if (result.Status == KeyCredentialStatus.Success)
                    {
                        UpdateAuthenticationStatus(true);
                        return(Result.Ok());
                    }
                    return(Result.Error("Windows Hello", $"Cannot sign in with Windows Hello: {result.Status}"));
                }
                return(Result.Error("Windows Hello", $"Cannot sign in with Windows Hello: {retrieveResult.Status}"));
            }
            return(Result.Error("Windows Hello", "Windows Hello is not enabled for current user."));
        }
Пример #18
0
        /// <summary>
        /// Create a passport key
        /// </summary>
        /// <exception cref="UserCancelledException"></exception>
        /// <exception cref="MissingPinException"></exception>
        /// <exception cref="UserPrefersPasswordException"></exception>
        /// <exception cref="UnknownException"></exception>
        /// <exception cref="AggregateException"></exception>
        /// <param name="accountId">The account id</param>
        public static void CreatePassportKey(string accountId)
        {
            // Run KeyCredentialManager.RequestCreateAsync to create the account.
            // Overwrites any existing accounts
            Task <KeyCredentialRetrievalResult> task = Task.Run(async() =>
                                                                await KeyCredentialManager.RequestCreateAsync(accountId, KeyCredentialCreationOption.ReplaceExisting));

            // Check the KeyCredentialRetrievalResult status
            switch (task.Result.Status)
            {
            case KeyCredentialStatus.Success:
                // The operation was successful
                return;

            case KeyCredentialStatus.UserCanceled:
                // User cancelled the Passport enrollment process
                throw new UserCancelledException();

            case KeyCredentialStatus.NotFound:
                // User needs to create PIN
                throw new MissingPinException();

            case KeyCredentialStatus.UserPrefersPassword:
                // The user prefers a password
                throw new UserPrefersPasswordException();

            default:
                // An unknown error occurred
                throw new UnknownException();
            }
        }
Пример #19
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;
            }
        }
Пример #20
0
 public AuthController(IIdentityServerInteractionService identity, AppUserManager userManager, SignInManager <AppUser> signInManager, KeyCredentialManager keyManager, ILogger <AuthController> logger)
 {
     _identity      = identity;
     _userManager   = userManager;
     _signInManager = signInManager;
     _keyManager    = keyManager;
     _logger        = logger;
 }
        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);
        }
Пример #22
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);
        }
Пример #23
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);
        }
Пример #24
0
 /// <summary>
 /// Requests the deletion of a Microsoft Key credential.
 /// </summary>
 /// <param name="credentialName">Name of the credential to be deleted.</param>
 internal static async void DeleteCredential(string credentialName)
 {
     try
     {
         await KeyCredentialManager.DeleteAsync(credentialName);
     }
     catch (Exception ev)
     {
         MessageService.ShowWarning("Credential not deleted: " + ev.Message);
         //Debug.Write("Expected exception: " + ev.Message);
     }
 }
Пример #25
0
        private async Task <bool> SignInWithHelloAsync()
        {
            LookupUser();

            // Open the existing user key credential.
            KeyCredentialRetrievalResult retrieveResult = await KeyCredentialManager.OpenAsync(userId);

            if (retrieveResult.Status != KeyCredentialStatus.Success)
            {
                return(false);
            }

            KeyCredential userCredential = retrieveResult.Credential;

            // Request a challenge from the server.
            JsonValue jsonChallenge = await JsonRequest.Create()
                                      .AddString("userId", userId)
                                      .AddString("publicKeyHint", publicKeyHint)
                                      .PostAsync("api/Authentication/RequestChallenge");

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

            // Sign the challenge using the user's KeyCredential.
            IBuffer challengeBuffer = CryptographicBuffer.DecodeFromBase64String(jsonChallenge.GetString());
            KeyCredentialOperationResult opResult = await userCredential.RequestSignAsync(challengeBuffer);

            if (opResult.Status != KeyCredentialStatus.Success)
            {
                return(false);
            }

            // Get the signature.
            IBuffer signatureBuffer = opResult.Result;

            // Send the signature back to the server to confirm our identity.
            // The publicKeyHint tells the server which public key to use to verify the signature.
            JsonValue jsonResult = await JsonRequest.Create()
                                   .AddString("userId", userId)
                                   .AddString("publicKeyHint", publicKeyHint)
                                   .AddString("signature", CryptographicBuffer.EncodeToBase64String(signatureBuffer))
                                   .PostAsync("api/Authentication/SubmitResponse");

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

            return(jsonResult.GetBoolean());
        }
Пример #26
0
        /// <summary>
        /// Creates a Passport key on the machine using the _account id passed.
        /// </summary>
        /// <param name="accountId">The _account id associated with the _account that we are enrolling into Passport</param>
        /// <returns>Boolean representing if creating the Passport key succeeded</returns>
        public static async Task <bool> CreatePassportKeyAsync(Guid userId, string username)
        {
            Debug.WriteLine("Before calling KeyCredentialManager.RequestCreateAsync");

            KeyCredentialRetrievalResult keyCreationResult = await KeyCredentialManager.RequestCreateAsync(username, KeyCredentialCreationOption.ReplaceExisting);

            Debug.WriteLine("After calling KeyCredentialManager.RequestCreateAsync");

            switch (keyCreationResult.Status)
            {
            case KeyCredentialStatus.Success:
                Debug.WriteLine("Successfully made key");

                // In the real world authentication would take place on a server.
                // So every time a user migrates or creates a new Microsoft Passport account Passport details should be pushed to the server.
                // The details that would be pushed to the server include:
                // The public key, keyAttesation if available,
                // certificate chain for attestation endorsement key if available,
                // status code of key attestation result: keyAttestationIncluded or
                // keyAttestationCanBeRetrievedLater and keyAttestationRetryType
                // As this sample has no concept of a server it will be skipped for now
                // for information on how to do this refer to the second Passport sample

                //For this sample just return true
                await GetKeyAttestationAsync(userId, keyCreationResult);

                return(true);

            case KeyCredentialStatus.UserCanceled:
                Debug.WriteLine("User cancelled sign-in process.");
                break;

            case KeyCredentialStatus.NotFound:
                // User needs to setup Microsoft Passport
                Debug.WriteLine("Microsoft Passport is not setup!\nPlease go to Windows Settings and set up a PIN to use it.");
                break;

            case KeyCredentialStatus.CredentialAlreadyExists:
                Debug.WriteLine("Credential already exists!");
                break;

            case KeyCredentialStatus.UnknownError:
                Debug.WriteLine("Unknown error generating credentials key");
                break;

            default:
                Debug.WriteLine("Some error making the credentials key!");
                break;
            }

            return(false);
        }
Пример #27
0
        private async Task <IBuffer> GetPassportAuthenticationMessage(IBuffer message, string accountId)
        {
            KeyCredentialRetrievalResult openKeyResult = await KeyCredentialManager.OpenAsync(accountId);

            if (openKeyResult.Status == KeyCredentialStatus.Success)
            {
                KeyCredential userKey   = openKeyResult.Credential;
                IBuffer       publicKey = userKey.RetrievePublicKey();

                KeyCredentialOperationResult signResult = await userKey.RequestSignAsync(message);

                if (signResult.Status == KeyCredentialStatus.Success)
                {
                    return(signResult.Result);
                }
                else if (signResult.Status == KeyCredentialStatus.UserCanceled)
                {
                    // User cancelled the Passport PIN entry.
                    //
                    // We will return null below this and the username/password
                    // sign in form will show.
                }
                else if (signResult.Status == KeyCredentialStatus.NotFound)
                {
                    // Must recreate Passport key
                }
                else if (signResult.Status == KeyCredentialStatus.SecurityDeviceLocked)
                {
                    // Can't use Passport right now, remember that hardware failed and suggest restart
                }
                else if (signResult.Status == KeyCredentialStatus.UnknownError)
                {
                    // Can't use Passport right now, try again later
                }

                return(null);
            }
            else if (openKeyResult.Status == KeyCredentialStatus.NotFound)
            {
                // Passport key lost, need to recreate it
                //textblock_PassportStatusText.Text = "Microsoft Passport is almost ready!\nPlease go to Windows Settings and set up a PIN to use it.";
                //grid_PassportStatus.Background = new SolidColorBrush(Color.FromArgb(255, 50, 170, 207));
                //button_PassportSignIn.IsEnabled = false;

                m_passportAvailable = false;
            }
            else
            {
                // Can't use Passport right now, try again later
            }
            return(null);
        }
Пример #28
0
        public static async Task <bool> testPassportAvailable()
        {
            bool x = await KeyCredentialManager.IsSupportedAsync();

            if (x == true)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #29
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
     {
     }
 }
        public static async Task <bool> CreatePassportKeyAsync()
        {
            KeyCredentialRetrievalResult keyCreationResult = await KeyCredentialManager.RequestCreateAsync("temp", KeyCredentialCreationOption.ReplaceExisting);

            if (keyCreationResult.Status == KeyCredentialStatus.Success)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }