UserConsentVerifier Класс

Определение

Проверяет доступность устройства проверки (например, ПИН-кода Microsoft Passport, Windows Hello биометрических данных или сканера отпечатков пальцев) и выполняет проверку.

public ref class UserConsentVerifier abstract sealed
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
class UserConsentVerifier final
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
public static class UserConsentVerifier
Public Class UserConsentVerifier
Наследование
Object Platform::Object IInspectable UserConsentVerifier
Атрибуты

Требования к Windows

Семейство устройств
Windows 10 (появилось в 10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (появилось в v1.0)

Примеры

Классические приложения, использующие C#

Для классического приложения вместо вызова метода UserConsentVerifier.RequestVerificationAsync вам потребуется:

private async System.Threading.Tasks.Task<string> RequestConsent(string userMessage)
{
    string returnMessage;

    // Retrieve the window handle of the current WinUI 3 window.
    var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(this);

    // Use the interop interface to request the logged on user's consent via device authentication
    var consentResult = await Windows.Security.Credentials.UI.UserConsentVerifierInterop.RequestVerificationForWindowAsync(hwnd, userMessage);

    switch (consentResult)
    {
        case Windows.Security.Credentials.UI.UserConsentVerificationResult.Verified:
            returnMessage = "User verified.";
            break;
        case Windows.Security.Credentials.UI.UserConsentVerificationResult.DeviceBusy:
            returnMessage = "Authentication device is busy.";
            break;
        case Windows.Security.Credentials.UI.UserConsentVerificationResult.DeviceNotPresent:
            returnMessage = "No authentication device found.";
            break;
        case Windows.Security.Credentials.UI.UserConsentVerificationResult.DisabledByPolicy:
            returnMessage = "Authentication device verification is disabled by policy.";
            break;
        case Windows.Security.Credentials.UI.UserConsentVerificationResult.NotConfiguredForUser:
            returnMessage = "Please go to Account Settings to set up PIN or other advanced authentication.";
            break;
        case Windows.Security.Credentials.UI.UserConsentVerificationResult.RetriesExhausted:
            returnMessage = "There have been too many failed attempts. Device authentication canceled.";
            break;
        case Windows.Security.Credentials.UI.UserConsentVerificationResult.Canceled:
            returnMessage = "Device authentication canceled.";
            break;
        default:
            returnMessage = "Authentication device is currently unavailable.";
            break;
    }

    return returnMessage;
}

универсальная платформа Windows приложений (UWP) с использованием C#

Этот пример кода предназначен для приложения универсальная платформа Windows (UWP). В нем отображается запрос на проверку отпечатков пальцев с последующим возвратом сообщения с описанием результата. Код вызывает метод UserConsentVerifier.RequestVerificationAsync , который подходит для приложений UWP.

private async System.Threading.Tasks.Task<string> RequestConsent(string userMessage)
{
    string returnMessage;

    // Request the logged on user's consent via authentication device.
    var consentResult = await Windows.Security.Credentials.UI.UserConsentVerifier.RequestVerificationAsync(userMessage);

    switch (consentResult)
    {
        case Windows.Security.Credentials.UI.UserConsentVerificationResult.Verified:
            returnMessage = "User verified.";
            break;
        case Windows.Security.Credentials.UI.UserConsentVerificationResult.DeviceBusy:
            returnMessage = "Authentication device is busy.";
            break;
        case Windows.Security.Credentials.UI.UserConsentVerificationResult.DeviceNotPresent:
            returnMessage = "No authentication device found.";
            break;
        case Windows.Security.Credentials.UI.UserConsentVerificationResult.DisabledByPolicy:
            returnMessage = "Authentication device verification is disabled by policy.";
            break;
        case Windows.Security.Credentials.UI.UserConsentVerificationResult.NotConfiguredForUser:
            returnMessage = "Please go to Account Settings to set up PIN or other advanced authentication.";
            break;
        case Windows.Security.Credentials.UI.UserConsentVerificationResult.RetriesExhausted:
            returnMessage = "There have been too many failed attempts. Device authentication canceled.";
            break;
        case Windows.Security.Credentials.UI.UserConsentVerificationResult.Canceled:
            returnMessage = "Device authentication canceled.";
            break;
        default:
            returnMessage = "Authentication device is currently unavailable.";
            break;
    }
    return returnMessage;
}

Классические приложения, использующие C++/WinRT

Для классического приложения вместо вызова метода UserConsentVerifier.RequestVerificationAsync вам потребуется:

  • Сначала получите дескриптор для окна, которое запросит проверку. Дополнительные сведения о том, как это сделать для библиотеки пользовательского интерфейса Windows (WinUI) 3, см. в разделе Получение дескриптора окна (HWND ).
  • Получите фабрику активации для объекта Windows.Security.Credentials.UI.UserConsentVerifier .
  • Вызовите метод RequestVerificationForWindowAsync интерфейса взаимодействия IUserConsentVerifierInterop .
winrt::Windows::Foundation::IAsyncOperation<winrt::hstring> MainWindow::RequestConsent(winrt::hstring userMessage)
{
    auto lifetime = get_strong();

    winrt::hstring returnMessage;

    // Retrieve the window handle of the current WinUI 3 window.
    HWND hwnd;
    winrt::check_hresult(m_inner->as<::IWindowNative>()->get_WindowHandle(&hwnd));

    // Use the interop interface to request the logged on user's consent via device authentication
    auto interop = winrt::get_activation_factory<winrt::Windows::Security::Credentials::UI::UserConsentVerifier, ::IUserConsentVerifierInterop>();
    auto consentResult =
        co_await winrt::capture<winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Security::Credentials::UI::UserConsentVerificationResult>>(
            interop, &::IUserConsentVerifierInterop::RequestVerificationForWindowAsync, hwnd, reinterpret_cast<HSTRING>(winrt::get_abi(userMessage))));

    switch (consentResult)
    {
        case winrt::Windows::Security::Credentials::UI::UserConsentVerificationResult::Verified:
            returnMessage = L"User verified.";
            break;
        case winrt::Windows::Security::Credentials::UI::UserConsentVerificationResult::DeviceBusy:
            returnMessage = L"Authentication device is busy.";
            break;
        case winrt::Windows::Security::Credentials::UI::UserConsentVerificationResult::DeviceNotPresent:
            returnMessage = L"No authentication device found.";
            break;
        case winrt::Windows::Security::Credentials::UI::UserConsentVerificationResult::DisabledByPolicy:
            returnMessage = L"Authentication device verification is disabled by policy.";
            break;
        case winrt::Windows::Security::Credentials::UI::UserConsentVerificationResult::NotConfiguredForUser:
            returnMessage = L"Please go to Account Settings to set up PIN or other advanced authentication.";
            break;
        case winrt::Windows::Security::Credentials::UI::UserConsentVerificationResult::RetriesExhausted:
            returnMessage = L"There have been too many failed attempts. Device authentication canceled.";
            break;
        case winrt::Windows::Security::Credentials::UI::UserConsentVerificationResult::Canceled:
            returnMessage = L"Device authentication canceled.";
            break;
        default:
            returnMessage = L"Authentication device is currently unavailable.";
            break;
    }

    co_return returnMessage;
}

Комментарии

UserConsentVerifier можно использовать для повышения безопасности приложения, включив запрос на проверку всякий раз, когда пользователю требуется согласие на определенное действие. Например, вы можете потребовать проверку подлинности по отпечатку пальца перед авторизацией покупки из приложения или доступа к ограниченным ресурсам. С помощью UserConsentVerifier можно определить, поддерживается ли проверка подлинности по отпечатку пальца для текущего компьютера с помощью метода CheckAvailabilityAsync , а затем запросить согласие пользователя из сканирования отпечатков пальцев с помощью метода RequestVerificationAsync .

Методы

CheckAvailabilityAsync()

Проверяет, доступно ли устройство проверки подлинности, например ПИН-код Microsoft Passport, Windows Hello или сканер отпечатков пальцев.

RequestVerificationAsync(String)

Выполняет проверку с помощью устройства проверки подлинности, такого как ПИН-код Microsoft Passport, Windows Hello или сканер отпечатков пальцев. Этот API предназначен для приложений универсальная платформа Windows (UWP). Альтернативный API для классического приложения описан в разделе Примерыв классе UserConsentVerifier.

Применяется к

См. также раздел