.NET MAUI中如何检测设备PIN/密码设置以实现登录安全校验
To check if a device has a PIN or password set across iOS, Android, and Windows in .NET MAUI, you'll need to use platform-specific implementations since there's no built-in cross-platform API for this. Here's a step-by-step solution:
1. Create a Shared Interface
First, define an interface in your shared project to abstract the platform-specific logic:
public interface IDeviceSecurityChecker { Task<bool> HasDeviceCredentialSetAsync(); }
2. Implement Platform-Specific Logic
Create platform-specific classes that implement the interface for each target OS.
Android Implementation
In Platforms/Android/DeviceSecurityChecker.cs:
using Android.App; using Android.Content; using Microsoft.Maui.ApplicationModel; namespace YourAppNamespace.Platforms.Android { public class DeviceSecurityChecker : IDeviceSecurityChecker { public Task<bool> HasDeviceCredentialSetAsync() { var context = Platform.CurrentActivity ?? Application.Context; var keyguardManager = (KeyguardManager)context.GetSystemService(Context.KeyguardService); // Returns true if device has PIN, pattern, or password set return Task.FromResult(keyguardManager.IsDeviceSecure); } } }
iOS Implementation
In Platforms/iOS/DeviceSecurityChecker.cs:
using LocalAuthentication; namespace YourAppNamespace.Platforms.iOS { public class DeviceSecurityChecker : IDeviceSecurityChecker { public Task<bool> HasDeviceCredentialSetAsync() { var context = new LAContext(); NSError error; // DeviceOwnerAuthentication requires either passcode or biometrics // Since biometrics can't be enabled without a passcode, this confirms passcode presence bool hasCredential = context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, out error); return Task.FromResult(hasCredential); } } }
Windows Implementation
In Platforms/Windows/DeviceSecurityChecker.cs:
using Windows.Security.Credentials.UI; namespace YourAppNamespace.Platforms.Windows { public class DeviceSecurityChecker : IDeviceSecurityChecker { public async Task<bool> HasDeviceCredentialSetAsync() { // Check if PIN is available var pinStatus = await UserConsentVerifier.CheckAvailabilityAsync(UserConsentVerifierAvailability.Pin); bool hasPin = pinStatus == UserConsentVerifierAvailability.Available; // Check if password is available var passwordStatus = await UserConsentVerifier.CheckAvailabilityAsync(UserConsentVerifierAvailability.Password); bool hasPassword = passwordStatus == UserConsentVerifierAvailability.Available; // Return true if either credential is set return hasPin || hasPassword; } } }
3. Register the Service
Add the service to your MauiProgram.cs to enable dependency injection:
namespace YourAppNamespace { public static class MauiProgram { public static MauiApp CreateMauiApp() { var builder = MauiApp.CreateBuilder(); builder .UseMauiApp<App>() .ConfigureFonts(fonts => { fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"); }); // Register the security checker service builder.Services.AddSingleton<IDeviceSecurityChecker>(sp => { #if ANDROID return new Platforms.Android.DeviceSecurityChecker(); #elif IOS return new Platforms.iOS.DeviceSecurityChecker(); #elif WINDOWS return new Platforms.Windows.DeviceSecurityChecker(); #else throw new NotSupportedException("Unsupported platform"); #endif }); return builder.Build(); } } }
4. Use the Service in Shared Code
Inject the IDeviceSecurityChecker into your view models or pages to check for credentials:
public class LoginViewModel : ObservableObject { private readonly IDeviceSecurityChecker _securityChecker; public LoginViewModel(IDeviceSecurityChecker securityChecker) { _securityChecker = securityChecker; } public async Task CheckDeviceSecurity() { bool hasCredential = await _securityChecker.HasDeviceCredentialSetAsync(); if (hasCredential) { // Proceed with biometric authentication (using Plugin.Fingerprint) } else { // Prompt user to set up a PIN/password in device settings } } }
Key Notes
- Android:
IsDeviceSecurechecks for PIN, pattern, or password (biometrics require one of these, so it will return true if biometrics are enabled). - iOS:
DeviceOwnerAuthenticationconfirms either passcode or biometrics are present. Since biometrics can't be enabled without a passcode, this guarantees a passcode exists if biometrics are active. - Windows: Checks both PIN and password availability to cover all secure sign-in methods.
内容的提问来源于stack exchange,提问作者WhyAlfred

