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);
			};
		}
		public BiometricsImpl() {
			this.context = new LAContext();
            this.available = new Lazy<bool>(() => {
    			NSError _;
	    		return this.context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out _);
            });
		}
		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);
		}
 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;
     }
 }
Exemple #5
0
 public bool SupportsFaceBiometric()
 {
     if (SystemMajorVersion() < 11)
     {
         return(false);
     }
     using (var context = new LAContext())
     {
         if (!context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out var e))
         {
             return(false);
         }
         return(context.BiometryType == LABiometryType.FaceId);
     }
 }
Exemple #6
0
        private static BiometryImplementation GetBiometryImplementation()
        {
            if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                var context = new LAContext();

                // Evaluate the Biometry policies. Even if the following call fails and returns fals, the
                // context.BiometryType field will still be set, and that's the only information we need.
                // See https://developer.apple.com/documentation/localauthentication/lacontext/1514149-canevaluatepolicy
                // for the doc. The return value is irrelevant for this specific purpose.
                //
                // This is important, because it is possible to get errors here due to various reasons.
                // Either the user has been locked out of Biometrys due to too many failed attempts, or
                // the device does not have an enrolled entity. In both cases, apps might require the
                // biometry type anyways to display an accurate message to the user.
                //
                // However, this behaviour does not seem to be the same accross all devices or iOS versions.
                // See this radar for more information about the bug https://openradar.appspot.com/36064151#ag9zfm9wZW5yYWRhci1ocmRyFAsSB0NvbW1lbnQYgICAuMqf8AgM
                // If for some reason the context.BiometryType was not set during the CanEvaluatePolicy call,
                // it will contain the value None (0). If such a value is held, we need to go through the
                // fallback procedure below.
                context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out NSError error);

                var systemVersion = new Version(UIDevice.CurrentDevice.SystemVersion);
                if (systemVersion >= _minimalVersionBiometryType)                 // Version 11.0.0 did not contain the BiometryType field. This means we cannot use CheckVersion because it only compares Major.Minor
                {
                    switch (context.BiometryType)
                    {
                    case LABiometryType.TouchId:
                        return(BiometryImplementation.TouchId);

                    case LABiometryType.FaceId:
                        return(BiometryImplementation.FaceId);

                    case LABiometryType.None:
                        return(BiometryImplementation.Unavailable);
                    }
                }

                else
                {
                    return(BiometryImplementation.TouchId);
                }
            }

            // Anything below iOS 8 does not support Biometrys
            return(BiometryImplementation.Unavailable);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.

            authenticationButton.TouchUpInside += (sender, e) =>
            {
                var context = new LAContext();
                var result  = context.EvaluatePolicyAsync(LAPolicy.DeviceOwnerAuthentication, "Authentication Request").GetAwaiter().GetResult();

                var can = context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out Foundation.NSError error);

                if (result.Item1)
                {
                    UserDialogs.Instance.Alert("Authentication");
                }
                else
                {
                    var code   = Convert.ToInt16(result.Item2.Code);
                    var status = (LAStatus)code;
                    UserDialogs.Instance.Alert(status.ToString());
                }
            };

            authenButton.TouchUpInside += (sender, e) =>
            {
                var context  = new LAContext();
                var myReason = new NSString("To add a new chore");

                if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out NSError AuthError))
                {
                    var replyHandler = new LAContextReplyHandler((success, error) => {
                        this.InvokeOnMainThread(() => {
                            if (success)
                            {
                                UserDialogs.Instance.Alert("Login Success");
                            }
                            else
                            {
                                //Show fallback mechanism here
                            }
                        });
                    });
                    context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, myReason, replyHandler);
                }
                ;
            };
        }
        private void CreateLaContext()
        {
            var info = new NSProcessInfo();

            if (!UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                return;
            }
            // Check LAContext is not available on iOS7 and below, so check LAContext after checking iOS version.
            if (Class.GetHandle(typeof(LAContext)) == IntPtr.Zero)
            {
                return;
            }

            _context = new LAContext();
        }
Exemple #9
0
        public void AuthenticateWithTouchId(LoginPage page)
        {
            var hasLoginKey = NSUserDefaults.StandardUserDefaults.BoolForKey("hasLogin");

            if (String.IsNullOrEmpty(App.UserName))
            {
                return;
            }

            var username = NSUserDefaults.StandardUserDefaults.ValueForKey(new NSString("username")).ToString();

            if (String.IsNullOrEmpty(username))
            {
                return;
            }

            var     context = new LAContext();
            NSError AuthError;
            var     myReason = new NSString("Login to expense portal");

            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
            {
                var replyHandler = new LAContextReplyHandler((success, error) => {
                    if (error != null)
                    {
                        if (error.LocalizedDescription == "Canceled by user.")
                        {
                            return;
                        }
                    }

                    if (success)
                    {
                        Console.WriteLine("Success!!");
                        var userName = NSUserDefaults.StandardUserDefaults.ValueForKey(new NSString("username")).ToString();

                        Xamarin.Insights.Identify(userName, new Dictionary <string, string> {
                            { "User Type", "NonApprover" },
                        });
                    }

                    page.TouchIdSuccess = success;
                });
                context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, myReason, replyHandler);
            }
            ;
        }
Exemple #10
0
        public Task <bool> GetAuthentication()
        {
            TaskCompletionSource <bool> tcs = new TaskCompletionSource <bool>();
            LAContext context = new LAContext();
            NSString  caption = new NSString("Login to tSecret");

            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out NSError ae))
            {
                LAContextReplyHandler replyHandler = new LAContextReplyHandler((success, error) =>
                {
                    tcs.SetResult(success);
                });
                context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, caption, replyHandler);
            }
            ;
            return(tcs.Task);
        }
Exemple #11
0
        public bool Authenticted()
        {
            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 (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
                    this.InvokeOnMainThread(() =>
                    {
                        if (success)
                        {
                            //Console.WriteLine($"You logged in with {BiometryType}!");

                            //PerformSegue("AuthenticationSegue", this);
                            IsValidFace = true;
                        }
                        else
                        {
                            IsValidFace = false;
                            //Console.WriteLine(error.LocalizedDescription);
                            //Show fallback mechanism here
                            //unAuthenticatedLabel.Text = $"{BiometryType} Authentication Failed";
                            //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);
                return(IsValidFace);
            }
            return(IsValidFace);
        }
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.");
                }
            }
        }
Exemple #13
0
        /// <inheritdoc />
        public Task <AuthenticationResult> AuthenticateAsync(string alertMessage = null)
        {
            if (AvailableBiometricType == BiometricType.None)
            {
                Logger.Debug("[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;

            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out authError) ||
                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 ?? "Please scan fingerprint", replyHandler);
            }
            else
            {
                //No Auth setup on Device
                Logger.Debug($"This device doesn't have authentication configured: {authError.ToString()}");
                tcs.TrySetResult(new AuthenticationResult(false, "This device does't have authentication configured."));
            }

            return(tcs.Task);
        }
Exemple #14
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);
            }
        }
Exemple #15
0
        public LocalAuthType GetLocalAuthType()
        {
            var localAuthContext = new LAContext();

            if (localAuthContext.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, out NSError AuthError))
            {
                if (localAuthContext.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
                {
                    if (GetOsMajorVersion() >= 11 && localAuthContext.BiometryType == LABiometryType.FaceId)
                    {
                        return(LocalAuthType.FaceId);
                    }
                    return(LocalAuthType.TouchId);
                }
                return(LocalAuthType.Passcode);
            }
            return(LocalAuthType.None);
        }
Exemple #16
0
        public bool HasFingerprint()
        {
            bool retVal = false;

            var context = new LAContext();

            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out var authError1))
            {
                context.LocalizedReason = "Authorize for access to STATALert"; // iOS 11

                if (context.BiometryType == LABiometryType.TouchId)
                {
                    retVal = true;
                }
            }

            return(retVal);
        }
Exemple #17
0
        public bool HasBiometrics()
        {
            bool retVal = false;

            var context = new LAContext();

            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out var authError))
            {
                retVal = true;

                if (authError != null)
                {
                    retVal = false;
                }
            }

            return(retVal);
        }
		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();
			}
		}
        /// <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);
            }
        }
Exemple #20
0
        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);
            }
        }
        /// <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);
        }
Exemple #22
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);
            }));
        }
Exemple #23
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);
        }
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);
            }
        }
        public async Task <LocalAuthResult> AuthenticateAsync(string reason)
        {
            var context = new LAContext
            {
                LocalizedFallbackTitle = "Fallback" // iOS 8
            };

            if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
            {
                context.LocalizedCancelTitle = "Cancel"; // iOS 10
            }
            if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
            {
                context.LocalizedReason = reason; // iOS 11
            }
            var rs = await AuthOnMainThreadAsync(context, reason);

            context.Dispose();
            return(rs);
        }
Exemple #26
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);
            }
        }
Exemple #27
0
        public void Authendicate()
        {
            //base.ViewWillAppear(animated);
            //unAuthenticatedLabel.Text = "";
            var context    = new LAContext();
            var buttonText = "";

            // Is login with biometrics possible?
            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out var authError1))
            {
                // has Touch ID or Face ID
                if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
                {
                    context.LocalizedReason = "Authorize for access to secrets"; // iOS 11
                    BiometryType            = context.BiometryType == LABiometryType.TouchId ? "Touch ID" : "Face ID";
                    buttonText = $"Login with {BiometryType}";
                }
                // No FaceID before iOS 11
                else
                {
                    buttonText = $"Login with Touch ID";
                }
            }

            // Is pin login possible?
            else if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, out var authError2))
            {
                buttonText   = $"Login"; // with device PIN
                BiometryType = "Device PIN";
            }

            // Local authentication not possible
            else
            {
                // Application might choose to implement a custom username/password
                buttonText   = "Use unsecured";
                BiometryType = "none";
            }

            //AuthenticateButton.SetTitle(buttonText, UIControlState.Normal);
        }
Exemple #28
0
        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);

            // bind every time, to reflect deletion in the Detail view
            LoginLabel.Text = "";

            // NOTE: following error will occur if the Info.plist key isn't set
            //Could not create an native instance of the type 'LocalAuthentication.LAContext': the native class hasn't been loaded.
            //It is possible to ignore this condition by setting ObjCRuntime.Class.ThrowOnInitFailure to false.
            var context = new LAContext();

            var buttonText = "";

            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out var authError1))
            { // has Biometrics (Touch or Face)
                if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
                {
                    context.LocalizedReason = "Authorize for access to secrets"; // iOS 11
                    BiometryType            = context.BiometryType == LABiometryType.TouchId ? "Touch ID" : "Face ID";
                    buttonText = $"Login with {BiometryType}";
                }
                else
                {   // no FaceID before iOS 11
                    buttonText = $"Login with Touch ID";
                }
            }
            else if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, out var authError2))
            {
                buttonText   = $"Login"; // with device PIN
                BiometryType = "Device PIN";
            }
            else
            {
                // Application might choose to implement a custom username/password
                buttonText   = "Use unsecured";
                BiometryType = "none";
            }
            LoginButton.SetTitle(buttonText, UIControlState.Normal);
            LoginButton.TouchUpInside += AuthenticateMe;
        }
        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);
            }
        }
Exemple #30
0
        public LocalAuthType GetLocalAuthType()
        {
            var     localAuthContext = new LAContext();
            NSError AuthError;

            if (localAuthContext.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, out AuthError))
            {
                if (localAuthContext.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
                {
#pragma warning disable CS0618 // Type or member is obsolete
                    if (GetOsMajorVersion() >= 11 && localAuthContext.BiometryType == LABiometryType.TypeFaceId)
#pragma warning restore CS0618 // Type or member is obsolete
                    {
                        return(LocalAuthType.FaceId);
                    }
                    return(LocalAuthType.TouchId);
                }
                return(LocalAuthType.Passcode);
            }
            return(LocalAuthType.None);
        }
        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);
            }
        }
Exemple #32
0
        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);
            }
        }
Exemple #33
0
        public static void Authenticate(Action onSuccess, Action onFailure)
        {
            var     context = new LAContext();
            NSError AuthError;

            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError) ||
                context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, out AuthError))
            {
                var replyHandler = new LAContextReplyHandler((success, error) =>
                {
                    if (success)
                    {
                        onSuccess?.Invoke();
                    }
                    else
                    {
                        onFailure?.Invoke();
                    }
                });
                context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, Strings.PleaseAuthenticateToProceed, replyHandler);
            }
        }
Exemple #34
0
        public void Authenticate(string userId, Action onSuccess, Action onFailure)
        {
            var context = new LAContext();

            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out NSError AuthError) ||
                context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, out AuthError))
            {
                var replyHandler = new LAContextReplyHandler((success, error) =>
                {
                    if (success)
                    {
                        onSuccess?.Invoke();
                    }
                    else
                    {
                        onFailure?.Invoke();
                    }
                });

                context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, $"Sign in with Online Id for {userId}", replyHandler);
            }
        }
Exemple #35
0
        public string GetAuthenticationType()
        {
            var     localAuthContext = new LAContext();
            NSError AuthError;

            if (localAuthContext.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, out AuthError))
            {
                if (localAuthContext.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
                {
                    if (GetOsMajorVersion() >= 11 && localAuthContext.BiometryType == LABiometryType.FaceId)
                    {
                        return("FaceId");
                    }

                    return("TouchId");
                }

                return("PassCode");
            }

            return("None");
        }
        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);
            }
        }
        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);
            }
        }
Exemple #38
0
        /// <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);
            };
        }
Exemple #39
0
 public static bool HaveBiometricsLogin()
 {
     var context = new LAContext();
     NSError AuthError;
     if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
     {
         context.Dispose();
         return true;
     }
     return false;
 }
		private void EvaluatePolicy ()
		{
			var context = new LAContext ();
			context.EvaluatePolicy (LAPolicy.DeviceOwnerAuthenticationWithBiometrics, Text.UNLOCK_ACCESS_TO_LOCKED_FATURE, HandleLAContextReplyHandler);
		}
 private void EvaluatePolicy(string reason)
 {
     if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) {
         var context = new LAContext ();
         context.EvaluatePolicy (LAPolicy.DeviceOwnerAuthenticationWithBiometrics, reason, HandleLAContextReplyHandler);
     } else {
         SystemLogger.Log (SystemLogger.Module.PLATFORM, "EvaluatePolicy - device OS is under iOS 8 - touch ID not available");
     }
 }
        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;
            }
        }
		public FingerprintAuthentication_iOS()
		{
			if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) {
				_context = new LAContext ();
			}
		}
        private void CreateLaContext()
        {
            if (Class.GetHandle(nameof(LAContext)) != IntPtr.Zero)
            {
                return;
            }

            _context = new LAContext();
        }