コード例 #1
0
		partial void AuthenticateMe (UIButton sender)
		{
			var context = new LAContext();
			NSError AuthError;
			var localizedReason = new NSString("To add a new chore");

			//Use canEvaluatePolicy method to test if device is TouchID enabled
			//Use the LocalAuthentication Policy DeviceOwnerAuthenticationWithBiometrics
			if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError)){
				replyHandler = new LAContextReplyHandler((success, error) => {
					//Make sure it runs on MainThread, not in Background
					this.InvokeOnMainThread(()=>{
						if(success){
							Console.WriteLine("You logged in!");
							PerformSegue("AuthenticationSegue", this);
						}
						else{
							//Show fallback mechanism here
							unAuthenticatedLabel.Text="Oh Noes";
							AuthenticateButton.Hidden= true;
						}
					});

				});
				//Use evaluatePolicy to start authentication operation and show the UI as an Alert view
				//Use the LocalAuthentication Policy DeviceOwnerAuthenticationWithBiometrics
				context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason, replyHandler);
			};
		}
		private void CanEvaluatePolicy ()
		{
			var context = new LAContext ();
			string message = string.Empty;
			NSError error;
			bool success = context.CanEvaluatePolicy (LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out error);
			message = success ? Text.TOUCH_ID_IS_AVAILABLE : Text.TOUCH_ID_IS_NOT_AVAILABLE;

			PrintResult (textView, message);
		}
コード例 #3
0
 public void BiometricsLogin()
 {
     var context = new LAContext();
     NSError AuthError;
     var myReason = new NSString(LoginScreenData.BioLoginMessage);
     if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
     {
         var replyHandler = new LAContextReplyHandler((success, error) =>
         {
             this.InvokeOnMainThread(() =>
             {
                 if (success)
                 {
                     var obj = Global.DatabaseManager.GetUsername();
                     var pwd = Encrypt.DecryptString(obj.PWD);
                     Dictionary<string, string> parameters = new Dictionary<string, string>();
                     parameters.Add("username", obj.Username);
                     parameters.Add("password", pwd);
                     parameters.Add("app_device_number", Device.DeviceID);
                     loginScreenView.Hide();
                     initLoadingScreenView(LoginScreenData.LoadingScreenTextLogin);
                     atimer = new Timer(1000);
                     atimer.Elapsed += (s, e) =>
                     {
                         if (ServerURLReady)
                         {
                             InvokeOnMainThread(() =>
                             {
                                 LoginWebCall(parameters);
                                 atimer.Stop();
                                 atimer.Dispose();
                             });
                         }
                     };
                     atimer.AutoReset = true;
                     atimer.Enabled = true;
                 }
                 else if (error!=null && error.ToString().Contains("Application retry limit exceeded")){
                     //Show fallback mechanism here
                     new UIAlertView(LoginScreenData.AlertScreenBioLoginFailTitle,
                                     error.ToString()+" "+LoginScreenData.AlertScreenBioLoginFaildMessage,
                                     null, LoginScreenData.AlertScreenBioLoginFaildCancelBtnTitle, null).Show();
                 }
                 PWDLogin();
             });
         });
         context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, myReason, replyHandler);
     }
     else {
         loginScreenView.userNameTextField.Hidden = false;
         loginScreenView.passwordTextField.Hidden = false;
         loginScreenView.loginBtn.Hidden = false;
         loginScreenView.fingerPrintView.Hidden = true;
     }
 }
コード例 #4
0
partial         void btnLogin_TouchUpInside(UIButton sender)
        {
            NSError _error;

            using (var _context = new LAContext ()) {

                // Allows us to reuse Touch ID verificaton from unlocking device up to 30 seconds later
                _context.TouchIdAuthenticationAllowableReuseDuration = 30;

                if (_context.CanEvaluatePolicy (LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out _error)) {

                    // Get enrollment state
                    if (_context.EvaluatedPolicyDomainState != null) {
                        var policyState = _context.EvaluatedPolicyDomainState.ToString().Replace("<", "").Replace(">", "").Replace(" ", "");

                        if (TouchIDPolicyDomainState != null)
                        {
                            if (policyState != TouchIDPolicyDomainState)
                                Console.WriteLine("Fingerprints enrollments changed.");
                            else
                                Console.WriteLine("Fingerprints enrollments remain the same.");
                        }

                        // Store enrollment
                        TouchIDPolicyDomainState = policyState;
                    }

                    var replyHandler = new LAContextReplyHandler ((success, error) => {
                        InvokeOnMainThread (() => {

                            if (success) {
                                PerformSegue("SegueToTest", null);
                            } else {
                                DisplayAlertOKPopup("", "Unable to authenticate.");
                            }
                        });
                    });

                    // Add reason why we are using Touch ID
                    _context.EvaluatePolicy (LAPolicy.DeviceOwnerAuthenticationWithBiometrics, "Login as user: X", replyHandler);
                } else {
                    DisplayAlertOKPopup("", "Touch ID not available on this device.");
                }
            }
        }
コード例 #5
0
        /// <summary>
        /// Views the will appear.
        /// </summary>
        /// <param name="animated">If set to <c>true</c> animated.</param>
        public override void ViewWillAppear(bool animated)
        {
            //get user connection profile
            ConnectionProfile connectionProfile = ConnectionHelper.GetConnectionProfile();

            if (connectionProfile == null)
            {
                return;
            }

            //create nre Local Auth context
            var     laContext = new LAContext();
            NSError AuthError;

            var authReason = new NSString("Connect to pet la forme");

            //if can evaluate policy with biometrics (FACE/TOUCH ID)
            if (laContext.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
            {
                //new reply handler
                var replyHandler = new LAContextReplyHandler((success, error) =>
                {
                    this.InvokeOnMainThread(() =>
                    {
                        if (success)
                        {
                            Auth(connectionProfile);
                        }
                        else
                        {
                            Console.WriteLine("Auth fail");
                        }
                    });
                });
                //evaluate policy in actual local context
                laContext.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, authReason, replyHandler);
            }
            else
            {
                //also connect user because ios simulator don't have secret code and biometrics
                Auth(connectionProfile);
            }
        }
コード例 #6
0
		partial void LoginButtonOnUpInside (UIButton sender)
		{
			if (!PerformValidation ()) {
				return;
			}
				
			var context = new LAContext();
			NSError AuthError;
			if (context.CanEvaluatePolicy (LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError)) {
				var replyHandler = new LAContextReplyHandler((success, error) => InvokeOnMainThread (() => {
					if (success) {
						AttemptLogin();
					} 
				}));
				context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, "Logging in with Touch ID", replyHandler);
			} else {
				AttemptLogin();
			}
		}
コード例 #7
0
        /// <summary>
        ///     Gets the device's current biometric capabilities.
        /// </summary>
        /// <returns>A <see cref="BiometryCapabilities" /> struct instance.</returns>
        public Task <BiometryCapabilities> GetCapabilities()
        {
            var context = new LAContext();

            context.CanEvaluatePolicy(_localAuthenticationPolicy, out var laError);

            var biometryType      = GetBiometryTypeFrom(context.BiometryType);
            var passcodeIsSet     = true;
            var biometryIsEnabled = true;

            if (laError != null)
            {
                // Online docs, but no error code values: https://developer.apple.com/documentation/localauthentication/laerror?language=objc
                // Source code docs found locally starting in dir:
                // /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/System/Library/Frameworks/LocalAuthentication.framework/Headers/LAError.h
                // /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/System/Library/Frameworks/LocalAuthentication.framework/Headers/LAPublicDefines.h
                // Double check for your platform just to be sure! /Applications/Xcode.app/Contents/Developer/Platforms/{X}.platform/...

                if (laError.Code == -5)
                {
                    // passcode/password not set on the device by the user
                    passcodeIsSet     = false;
                    biometryIsEnabled = false;
                }

                if (laError.Code == -6)
                {
                    // biometrics not available (no hardware support OR user has disabled FaceID/TouchID for the app)
                    biometryIsEnabled = false;
                }

                if (laError.Code == -7)
                {
                    // biometrics not enrolled (no finger xor face was added by the user)
                    biometryIsEnabled = false;
                }
            }
            return(Task.Run(() =>
            {
                return new BiometryCapabilities(biometryType, biometryIsEnabled, passcodeIsSet);
            }));
        }
コード例 #8
0
        /// <summary>
        /// Auths the on main thread.
        /// </summary>
        /// <returns>The on main thread.</returns>
        /// <param name="context">Context.</param>
        /// <param name="reason">Reason can not be null or empty</param>
        private Task <LocalAuthResult> AuthOnMainThreadAsync(LAContext context, string reason)
        {
            var tcs    = new TaskCompletionSource <LocalAuthResult>();
            var result = new LocalAuthResult(false);

            /* ==================================================================================================
             * indicate not allow null or empty reason
             * ================================================================================================*/
            if (string.IsNullOrWhiteSpace(reason))
            {
                result = new LocalAuthResult(false, "Your reason can not be null or empty");
                tcs.SetResult(result);
                return(tcs.Task);
            }

            /* ==================================================================================================
             * indicate the hardware
             * ================================================================================================*/
            if (!context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out NSError authError))
            {
                result = new LocalAuthResult(false, authError?.ToString());
                tcs.SetResult(result);
                return(tcs.Task);
            }

            /* ==================================================================================================
             * begin auth
             * ================================================================================================*/
            var nsReason     = new NSString(reason);
            var evaluateTask = context.EvaluatePolicyAsync(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, nsReason);

            evaluateTask.ContinueWith(t =>
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    var rs = t.Result;
                    result = new LocalAuthResult(rs.Item1, rs.Item2?.ToString());
                    tcs.SetResult(result);
                });
            });
            return(tcs.Task);
        }
コード例 #9
0
ファイル: MainView.cs プロジェクト: griosha/test123
        private void AddFingerprintAuthentication()
        {
            var     context = new LAContext();
            NSError authError;
            var     myReason = new NSString(
                "Please, provide your fingerprint to simplify the authentication.");

            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out authError))
            {
                var replyHandler = new LAContextReplyHandler((success, error) =>
                {
                    this.InvokeOnMainThread(() =>
                    {
                        var dialogService = Mvx.Resolve <IDialogService>();

                        if (success)
                        {
                            Settings.TouchIdEnrolledAndFingerprintDetected = true;

                            dialogService.AlertAsync(
                                "Your fingerprint was successfully detected. " +
                                "You can access the app through it from now on. " +
                                "Thank you.",
                                "Touch ID",
                                "OK");
                        }
                        else
                        {
                            Settings.TouchIdEnrolledAndFingerprintDetected = false;

                            dialogService.AlertAsync(
                                "We could not detect your fingerprint. " +
                                "You will need to authenticate through Azure AD. " +
                                "Thank you.",
                                "Touch ID",
                                "OK");
                        }
                    });
                });
                context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, myReason, replyHandler);
            }
        }
コード例 #10
0
        public bool IsFaceIDSupported()
        {
            var context = new LAContext();

            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out var authError))
            {
                if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
                {
                    return(context.BiometryType == LABiometryType.FaceId);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
コード例 #11
0
        static bool IsPasscodePresent()
        {
            var     context = new LAContext();
            NSError error;
            var     result = context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out error);

            switch ((LAStatus)((long)error.Code))
            {
            case LAStatus.PasscodeNotSet:
                result = false;
                break;

            case LAStatus.TouchIDNotAvailable:
            case LAStatus.TouchIDNotEnrolled:
                result = true;
                break;
            }

            return(result);
        }
コード例 #12
0
partial         void UIButton5_TouchUpInside(UIButton sender)
        {
            var context = new LAContext ();

            var error = new NSError ();

            if (context.CanEvaluatePolicy (LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error)) {

                var replyHandler = new LAContextReplyHandler((success, err) => {
                    this.InvokeOnMainThread(() => {
                        if(success){
                            new UIAlertView("Success", "You logged in", null, "Close").Show();
                        } else {
                            new UIAlertView("Login Error", err.LocalizedDescription, null, "Close").Show();
                        }
                    });
                });
                context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, "You need to login", replyHandler);
            }
        }
コード例 #13
0
        void LaunchTouchID()
        {
            var     context = new LAContext();
            NSError AuthError;
            var     reason = new NSString("Security validation");

            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
            {
                var replyHandler = new LAContextReplyHandler((success, error) =>
                {
                    this.InvokeOnMainThread(() =>
                    {
                        if (success)
                        {
                            DismissViewController(false, null);
                        }
                    });
                });
                context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, reason, replyHandler);
            }
        }
コード例 #14
0
        public async Task <bool> Authenticate(CancellationToken ct)
        {
            if (this.Log().IsEnabled(LogLevel.Debug))
            {
                this.Log().Debug("Authenticating the fingerprint.");
            }

            await AssertTouchIdIsEnabled(ct);

            using (await _asyncLock.LockAsync(ct))
            {
                var context = new LAContext();

                // Using LAPolicy.DeviceOwnerAuthentication will make authentication fallback on the passcode if touch id fails.
                var authenticationPolicy = _fallbackOnPasscodeAuthentication ? LAPolicy.DeviceOwnerAuthentication : LAPolicy.DeviceOwnerAuthenticationWithBiometrics;

                // Must call CanEvaluatePolicy before LAContext.BiometryType can be read
                var canEvaluatePolicy = context.CanEvaluatePolicy(authenticationPolicy, out NSError error);

                if (canEvaluatePolicy && context.BiometryType == LABiometryType.FaceId)
                {
                    // Verify that info.plist Contains NSFaceIDUsageDescription otherwise the app will crash when it tries to authenticate
                    string faceIDUsageDescription = ((NSString)NSBundle.MainBundle.InfoDictionary["NSFaceIDUsageDescription"])?.ToString();

                    if (string.IsNullOrEmpty(faceIDUsageDescription))
                    {
                        throw new MissingFieldException("Please add a NSFaceIDUsageDescription key in Info.plist");
                    }
                }

                var(result, _) = await context.EvaluatePolicyAsync(authenticationPolicy, await _description(ct));

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

                return(result);
            }
        }
コード例 #15
0
ファイル: MainView.cs プロジェクト: griosha/test123
        private void AuthenticateThroughFingerprint()
        {
            var     context = new LAContext();
            NSError authError;
            var     myReason = new NSString(
                "Please, provide your fingerprint to access the app.");

            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out authError))
            {
                var replyHandler = new LAContextReplyHandler((success, error) =>
                {
                    this.InvokeOnMainThread(async() =>
                    {
                        if (success)
                        {
                            await AuthenticateThroughAzureADAsync();
                            return;
                        }

                        var dialogService = Mvx.Resolve <IDialogService>();
                        await dialogService.AlertAsync(
                            "We could not detect your fingerprint. " +
                            "You will be asked again to enter your Azure AD credentials. " +
                            "Thank you.",
                            "Touch ID",
                            "OK");

                        // Since we're waking up, we need to silently sign in, and
                        // sign out just after to clear local cache
                        await AuthenticateThroughAzureADAsync();
                        SignOutFromAzureAD();

                        // If fingerprint not detected, repeat Azure AD auth.
                        await AuthenticateThroughAzureADAndAddFingerprintAsync()
                        .ConfigureAwait(false);
                    });
                });
                context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, myReason, replyHandler);
            }
        }
コード例 #16
0
        void LaunchTouchID()
        {
            var     context = new LAContext();
            NSError AuthError;
            var     reason = new NSString("Security validation");

            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
            {
                var replyHandler = new LAContextReplyHandler((success, error) =>
                {
                    this.InvokeOnMainThread(() =>
                    {
                        if (success)
                        {
                            //go to initial page
                            UIViewController uiview = Storyboard.InstantiateViewController("MainViewController");
                            PresentViewController(uiview, false, null);
                        }
                    });
                });
                context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, reason, replyHandler);
            }
        }
コード例 #17
0
        partial void UIButton5_TouchUpInside(UIButton sender)
        {
            var context = new LAContext();

            var error = new NSError();

            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error))
            {
                var replyHandler = new LAContextReplyHandler((success, err) => {
                    this.InvokeOnMainThread(() => {
                        if (success)
                        {
                            new UIAlertView("Success", "You logged in", null, "Close").Show();
                        }
                        else
                        {
                            new UIAlertView("Login Error", err.LocalizedDescription, null, "Close").Show();
                        }
                    });
                });
                context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, "You need to login", replyHandler);
            }
        }
コード例 #18
0
        public void FaceAuthentication()
        {
            var     context  = new LAContext();
            var     myReason = new NSString("Athenticate");
            NSError AuthError;

            //Check if Face ID is available on mobile device.
            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
            {
                var replyHandler = new LAContextReplyHandler((success, error) => {
                    Device.BeginInvokeOnMainThread(() => {
                        //If authetification is successfull navigate to Select Type page.

                        //If authentication is successful continue to next page.
                        if (success)
                        {
                            if (count > 0)                             // If record count for User table is > 0 then an account exist
                            {
                                Xamarin.Forms.Application.Current.MainPage = new Home();
                            }
                            else                             // If the record count is 0 then no User account exist
                            {
                                Xamarin.Forms.Application.Current.MainPage = new SelectType();
                            }
                        }
                    });
                });

                //Handle the result of Face ID authentification (Sucess/Failure) according to replyHandler above.
                context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, myReason, replyHandler);
            }
            else
            {
                //If FaceID NOT available on mobile device, display appropriate error message.
                Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Authentication Failed", "Could not Authenticate with FaceID", "Ok");
            }
        }
コード例 #19
0
        public override async Task <FingerprintAvailability> GetAvailabilityAsync(bool allowAlternativeAuthentication = false, bool getAvailabilityType = false)
        {
            NSError error;

            if (_context == null)
            {
                return(FingerprintAvailability.NoApi);
            }

            var policy = GetPolicy(allowAlternativeAuthentication);

            if (_context.CanEvaluatePolicy(policy, out error))
            {
                if (getAvailabilityType && UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
                {
                    return(_context.BiometryType == LABiometryType.TouchId ? FingerprintAvailability.AvailableTouchID : FingerprintAvailability.AvailableFaceID);
                }
                else
                {
                    return(FingerprintAvailability.Available);
                }
            }

            switch ((LAStatus)(int)error.Code)
            {
            case LAStatus.TouchIDNotAvailable:
                return(FingerprintAvailability.NoSensor);

            case LAStatus.TouchIDNotEnrolled:
            case LAStatus.PasscodeNotSet:
                return(FingerprintAvailability.NoFingerprint);

            default:
                return(FingerprintAvailability.Unknown);
            }
        }
コード例 #20
0
        /// <summary>
        /// Authenticates the user.
        /// </summary>
        public static void AuthenticateUser(MvxViewController controller)
        {
            var     viewModel = (AuthenticationViewModel)controller.ViewModel;
            var     context   = new LAContext();
            NSError AuthError;
            var     authenticationReason = new NSString("Authentication is needed to access the application");

            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
            {
                var replyHandler = new LAContextReplyHandler((success, error) =>
                {
                    controller.InvokeOnMainThread(() =>
                    {
                        if (viewModel != null)
                        {
                            if (success)
                            {
                                //Calling the success handler
                                viewModel.OnAuthenticationSuccess();
                                Console.WriteLine("You logged in!");
                            }
                            else
                            {
                                //Calling the failure handler
                                viewModel.OnAuthenticationFailure();
                            }
                        }
                    });
                });
                context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, authenticationReason, replyHandler);
            }
            else
            {
                viewModel.OnAuthenticationFailure();
            }
        }
コード例 #21
0
        private bool CanEvaluatePolicy()
        {
            if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) {
                var context = new LAContext ();
                string message = string.Empty;
                NSError error;
                bool success = context.CanEvaluatePolicy (LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out error);

                SystemLogger.Log (SystemLogger.Module.PLATFORM, "CanEvaluatePolicy - " + (success ? "Touch ID is available" : "Touch ID is not available"));
                return success;
            } else {
                SystemLogger.Log (SystemLogger.Module.PLATFORM, "CanEvaluatePolicy - device OS is under iOS 8 - touch ID not available");
                return false;
            }
        }
コード例 #22
0
        public void EscanearHuella()
        {
            try
            {
                var     context = new LAContext();
                NSError AuthError;
                var     localizedReason = new NSString("Por favor, coloque su dedo en el sensor");
                context.LocalizedFallbackTitle = "";

                bool touchIDSetOnDevice = context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError);

                //Use el método canEvaluatePolicy para probar si el dispositivo está habilitado para TouchID
                if (touchIDSetOnDevice)
                {
                    replyHandler = new LAContextReplyHandler((success, error) => {
                        //Asegúrese de que se ejecute en el hilo principal, no en el fondo
                        this.InvokeOnMainThread(() => {
                            if (success)
                            {
                                //Se ejecuta cuando la validación de la huella fue exitosa
                                Xamarin.Forms.Application.Current.MainPage.Navigation.PushModalAsync(new MainPage());
                            }
                            else
                            {
                                //Se ejecuta cuando no se pudo validar la huella
                                if (!error.LocalizedDescription.Equals("Canceled by user."))
                                {
                                    if (error.LocalizedDescription.Equals("Application retry limit exceeded."))
                                    {
                                        Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Atención", "Sólo le restan 2 intentos. ¿Seguro que desea continuar?", "Aceptar");
                                    }
                                    if (error.LocalizedDescription.Equals("Biometry is locked out."))
                                    {
                                        Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Atención", "Por su seguridad, su ingreso mediante huella dactilar fue desactivado.", "Aceptar");
                                    }
                                }
                            }
                        });
                    });
                    //Utilice evaluatePolicy para iniciar la operación de autenticación y mostrar la interfaz de usuario como una vista de alerta
                    context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason, replyHandler);
                }
                else
                {
                    if ((LAStatus)Convert.ToInt16(AuthError.Code) == LAStatus.TouchIDNotAvailable)
                    {
                        Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Atención", "Ingreso mediante huella dactilar no disponible.", "Aceptar");
                    }
                    else if ((LAStatus)Convert.ToInt16(AuthError.Code) == LAStatus.TouchIDNotEnrolled)
                    {
                        Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Atención", "No hay huellas dactilares registradas.", "Aceptar");
                    }
                    else if ((LAStatus)Convert.ToInt16(AuthError.Code) == LAStatus.BiometryNotAvailable)
                    {
                        Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Atención", "Este dispositivo no soporta la autenticación de huella dactilar.", "Aceptar");
                    }
                    //if((LAStatus)Convert.ToInt16(AuthError.Code) == LAStatus.BiometryNotEnrolled)
                    //Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Atención", "El usuario no se ha inscrito para la autenticación de huella dactilar.", "Aceptar");
                    else
                    {
                        HabilitarTecladoDesbloqueo();
                    }
                }
            }
            catch (Exception ex)
            {
                var e = ex;
            }
        }
コード例 #23
0
        /// <inheritdoc />
        public Task <AuthenticationResult> AuthenticateAsync(string alertMessage = null)
        {
            if (AvailableBiometricType == BiometricType.None)
            {
                Console.WriteLine("[BiometricAthenticationService] Authentication not available on this device");
                return(Task.FromResult(new AuthenticationResult(false, "Authentication not available")));
            }

            var tcs = new TaskCompletionSource <AuthenticationResult>();

            var     context = new LAContext();
            NSError authError;

            // Because LocalAuthentication APIs have been extended over time,
            // you must check iOS version before setting some properties
            context.LocalizedFallbackTitle = "Fallback";

            if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
            {
                context.LocalizedCancelTitle = "Cancel";
            }
            if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
            {
                context.LocalizedReason = "Authorize for access to secrets";
                BiometryType            = context.BiometryType == LABiometryType.TouchId ? "TouchID" : "FaceID";
                Console.WriteLine(BiometryType);
            }

            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out authError))
            {
                var replyHandler = new LAContextReplyHandler((success, error) =>
                {
                    //Make sure it runs on MainThread, not in Background
                    UIApplication.SharedApplication.InvokeOnMainThread(() =>
                    {
                        if (success)
                        {
                            System.Diagnostics.Debug.WriteLine("Authentication Success");
                            tcs.TrySetResult(new AuthenticationResult(true));
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine("Authentication Failure : " + error.Description);
                            tcs.TrySetResult(new AuthenticationResult(false, error.Description));
                        }
                    });
                });

                context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, alertMessage ?? localizedReason, replyHandler);
            }

            else if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, out authError))
            {
                var replyHandler = new LAContextReplyHandler((success, error) =>
                {
                    //Make sure it runs on MainThread, not in Background
                    UIApplication.SharedApplication.InvokeOnMainThread(() =>
                    {
                        if (success)
                        {
                            System.Diagnostics.Debug.WriteLine("Authentication Success");
                            tcs.TrySetResult(new AuthenticationResult(true));
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine("Authentication Failure : " + error.Description);
                            tcs.TrySetResult(new AuthenticationResult(false, error.Description));
                        }
                    });
                });

                context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, alertMessage ?? localizedReason, replyHandler);
            }
            else
            {
                //No Auth setup on Device
                Console.WriteLine($"This device doesn't have authentication configured: {authError.ToString()}");
                tcs.TrySetResult(new AuthenticationResult(false, "This device does't have authentication configured."));
            }

            return(tcs.Task);
        }
コード例 #24
0
        void AuthenticateMe(object sender, EventArgs ea)
        {
            var     context = new LAContext();
            NSError AuthError;
            var     localizedReason = new NSString("To access secrets");

            // because LocalAuthentication APIs have been extended over time, need to check iOS version before setting some properties
            context.LocalizedFallbackTitle = "Fallback"; // iOS 8

            if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
            {
                context.LocalizedCancelTitle = "Cancel"; // iOS 10
            }
            if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
            {
                context.LocalizedReason = "Authorize for access to secrets"; // iOS 11
                BiometryType            = context.BiometryType == LABiometryType.TouchId ? "TouchID" : "FaceID";
            }

            //Use canEvaluatePolicy method to test if device is TouchID or FaceID enabled
            //Use the LocalAuthentication Policy DeviceOwnerAuthenticationWithBiometrics
            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
            {
                Console.WriteLine("TouchID/FaceID available/enrolled");
                replyHandler = new LAContextReplyHandler((success, error) =>
                {
                    //Make sure it runs on MainThread, not in Background
                    InvokeOnMainThread(() =>
                    {
                        if (success)
                        {
                            Console.WriteLine($"You logged in with {BiometryType}!");

                            Nav.Authenticated = true;
                            DismissViewController(true, null);
                        }
                        else
                        {
                            Console.WriteLine(error.LocalizedDescription);
                            //Show fallback mechanism here
                            LoginLabel.Text = $"{BiometryType} Authentication Failed";
                            //LoginButton.Hidden = true;
                        }
                    });
                });
                //Use evaluatePolicy to start authentication operation and show the UI as an Alert view
                //Use the LocalAuthentication Policy DeviceOwnerAuthenticationWithBiometrics
                context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason, replyHandler);
            }
            else if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, out AuthError))
            {
                Console.WriteLine("When TouchID/FaceID aren't available or enrolled, use the device PIN");
                replyHandler = new LAContextReplyHandler((success, error) =>
                {
                    //Make sure it runs on MainThread, not in Background
                    InvokeOnMainThread(() =>
                    {
                        if (success)
                        {
                            Console.WriteLine($"You logged in with {BiometryType}!");

                            Nav.Authenticated = true;
                            DismissViewController(true, null);
                        }
                        else
                        {
                            Console.WriteLine(error.LocalizedDescription);
                            //Show fallback mechanism here
                            LoginLabel.Text = "Device PIN Authentication Failed";
                            //LoginButton.Hidden = true;
                        }
                    });
                });
                //Use evaluatePolicy to start authentication operation and show the UI as an Alert view
                //Use the LocalAuthentication Policy DeviceOwnerAuthenticationWithBiometrics
                context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, localizedReason, replyHandler);
            }
            else
            {
                // User hasn't configured a PIN or any biometric auth.
                // App may implement its own login, or choose to allow open access
                //unAuthenticatedLabel.Text = "No device auth configured";

                var okCancelAlertController = UIAlertController.Create("No authentication", "This device does't have authentication configured.", UIAlertControllerStyle.Alert);
                okCancelAlertController.AddAction(UIAlertAction.Create("Use unsecured", UIAlertActionStyle.Default, alert => DismissViewController(true, null)));
                okCancelAlertController.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, alert => Console.WriteLine("Cancel was clicked")));
                PresentViewController(okCancelAlertController, true, null);
            }
        }
コード例 #25
0
ファイル: Device.cs プロジェクト: MADMUC/TAP5050
 public static bool HaveBiometricsLogin()
 {
     var context = new LAContext();
     NSError AuthError;
     if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
     {
         context.Dispose();
         return true;
     }
     return false;
 }
コード例 #26
0
        private bool CheckEnrollment()
        {
            var context = new LAContext();

            return(context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out var error) || (error.Code != -5 && error.Code != -7));
        }
コード例 #27
0
        public Task <bool> AuthenticateMe()
        {
            var     context = new LAContext();
            NSError AuthError;
            var     localizedReason = new NSString("To access secrets");

            // because LocalAuthentication APIs have been extended over time, need to check iOS version before setting some properties
            context.LocalizedFallbackTitle = "Fallback"; // iOS 8

            if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
            {
                context.LocalizedCancelTitle = "Cancel"; // iOS 10
            }
            if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
            {
                context.LocalizedReason = "Authorize for access to secrets"; // iOS 11
                BiometryType            = context.BiometryType == LABiometryType.TouchId ? "TouchID" : "FaceID";
            }

            var tcs = new TaskCompletionSource <bool>();

            //Use canEvaluatePolicy method to test if device is TouchID or FaceID enabled
            //Use the LocalAuthentication Policy DeviceOwnerAuthenticationWithBiometrics
            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
            {
                Console.WriteLine("TouchID/FaceID available/enrolled");
                replyHandler = new LAContextReplyHandler((success, error) => {
                    //Make sure it runs on MainThread, not in Background
                    UIApplication.SharedApplication.InvokeOnMainThread(() => {
                        if (success)
                        {
                            Console.WriteLine($"You logged in with {BiometryType}!");
                            tcs.SetResult(success);
                            //PerformSegue("AuthenticationSegue", this);
                        }
                        else
                        {
                            Console.WriteLine(error.LocalizedDescription);
                            //Show fallback mechanism here
                            tcs.SetResult(success);
                            tcs.SetException(new Exception(error.Description));
                        }
                    });
                });
                //Use evaluatePolicy to start authentication operation and show the UI as an Alert view
                //Use the LocalAuthentication Policy DeviceOwnerAuthenticationWithBiometrics
                context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason, replyHandler);
            }
            else if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, out AuthError))
            {
                Console.WriteLine("When TouchID/FaceID aren't available or enrolled, use the device PIN");
                replyHandler = new LAContextReplyHandler((success, error) => {
                    //Make sure it runs on MainThread, not in Background
                    UIApplication.SharedApplication.InvokeOnMainThread(() => {
                        if (success)
                        {
                            Console.WriteLine($"You logged in with {BiometryType}!");
                            //PerformSegue("AuthenticationSegue", this);
                            tcs.SetResult(success);
                        }
                        else
                        {
                            Console.WriteLine(error.LocalizedDescription);
                            //Show fallback mechanism here
                            tcs.SetResult(success);
                            tcs.SetException(new Exception(error.Description));
                        }
                    });
                });
                //Use evaluatePolicy to start authentication operation and show the UI as an Alert view
                //Use the LocalAuthentication Policy DeviceOwnerAuthenticationWithBiometrics
                context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, localizedReason, replyHandler);
            }
            else
            {
                // User hasn't configured a PIN or any biometric auth.
                // App may implement its own login, or choose to allow open access
                tcs.SetResult(false);
            }

            return(tcs.Task);
        }
コード例 #28
0
ファイル: ViewController.cs プロジェクト: nielscup/ImageCrop
        /// <summary>
        /// TouchId authentication test
        /// </summary>
        private void AuthenticateMe()
        {
            var context = new LAContext();
            NSError AuthError;
            var myReason = new NSString("Login to take a picture");

            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
            {
                var replyHandler = new LAContextReplyHandler((success, error) =>
                {
                    this.InvokeOnMainThread(() =>
                    {
                        if (success)
                        {
                            Console.WriteLine("You logged in!");
                            _authenticateButton.Hidden = true;
                            Initialize();
                        }
                        else
                        {
                            // Inform the user authentication failed
                        }
                    });

                });
                context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, myReason, replyHandler);
            };
        }