public FingerprintService( FragmentActivity fragmentActivity, Context applicationContext, IObservable <Unit> applicationActivated, CoreDispatcher dispatcher, IScheduler backgroundScheduler, FuncAsync <BiometricPrompt.PromptInfo> promptInfoBuilder) { fragmentActivity.Validation().NotNull(nameof(fragmentActivity)); applicationActivated.Validation().NotNull(nameof(applicationActivated)); backgroundScheduler.Validation().NotNull(nameof(backgroundScheduler)); _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher)); _promptInfoBuilder = promptInfoBuilder ?? throw new ArgumentNullException(nameof(promptInfoBuilder)); var executor = ContextCompat.GetMainExecutor(applicationContext); var callback = new AuthenticationCallback(OnAuthenticationSucceeded, OnAuthenticationFailed, OnAuthenticationError); _BiometricPrompt = new BiometricPrompt(fragmentActivity, executor, callback); _BiometricManager = BiometricManager.From(Application.Context); _keyStore = KeyStore.GetInstance(ANDROID_KEYSTORE); _keyStore.Load(null); _canAuthenticate = applicationActivated .ObserveOn(backgroundScheduler) .StartWith(backgroundScheduler, Unit.Default) .Select(_ => _BiometricManager.CanAuthenticate()) .Replay(1, backgroundScheduler) .RefCount(); }
// Initialize CameraX, and prepare to bind the camera use cases private void SetUpCamera() { var cameraProviderFuture = ProcessCameraProvider.GetInstance(RequireContext()); cameraProviderFuture.AddListener(new Java.Lang.Runnable(() => { // CameraProvider cameraProvider = cameraProviderFuture.Get() as ProcessCameraProvider;; // Select lensFacing depending on the available cameras if (HasBackCamera()) { lensFacing = CameraSelector.LensFacingBack; } else if (HasFrontCamera()) { lensFacing = CameraSelector.LensFacingFront; } else { throw new Java.Lang.IllegalStateException("Back and front camera are unavailable"); } // Enable or disable switching between cameras UpdateCameraSwitchButton(); // Build and bind the camera use cases BindCameraUseCases(); }), ContextCompat.GetMainExecutor(RequireContext())); }
public void EnableBiometrics(Action <bool> callback) { var passwordStorage = new PasswordStorageManager(this); var executor = ContextCompat.GetMainExecutor(this); var authCallback = new AuthenticationCallback(); authCallback.Success += async(_, result) => { try { var password = await SecureStorageWrapper.GetDatabasePassword(); passwordStorage.Store(password, result.CryptoObject.Cipher); } catch (Exception e) { Logger.Error(e); callback(false); return; } callback(true); }; authCallback.Failed += delegate { callback(false); }; authCallback.Error += delegate { // Do something, probably callback(false); }; var prompt = new BiometricPrompt(this, executor, authCallback); var promptInfo = new BiometricPrompt.PromptInfo.Builder() .SetTitle(GetString(Resource.String.setupBiometricUnlock)) .SetNegativeButtonText(GetString(Resource.String.cancel)) .SetConfirmationRequired(false) .SetAllowedAuthenticators(BiometricManager.Authenticators.BiometricStrong) .Build(); Cipher cipher; try { cipher = passwordStorage.GetEncryptionCipher(); } catch (Exception e) { Logger.Error(e); passwordStorage.Clear(); callback(false); return; } prompt.Authenticate(promptInfo, new BiometricPrompt.CryptoObject(cipher)); }
public void Authenticate(Func <Task> action, string title) { try { switch (BiometricManager.From(_context).CanAuthenticate()) { case BiometricManager.BiometricSuccess: var biometricPrompt = new BiometricPrompt(MainActivity, ContextCompat.GetMainExecutor(_context), GetBiometricAuthenticationCallback(action)); var promptInfo = new BiometricPrompt.PromptInfo.Builder() .SetTitle(title == null ? "Biometric login for Falcon" : $"{title}...") .SetNegativeButtonText("Cancel") .Build(); biometricPrompt.Authenticate(promptInfo); return; case BiometricManager.BiometricErrorHwUnavailable: Tools.DisplayAlert(message: "Biometric hardware is currently unavailable. Try again later."); return; case BiometricManager.BiometricErrorNoneEnrolled: Tools.DisplayAlert(message: "The device does not have any biometrics enrolled. Please make sure you have set up any available biometrics in your phone Settings."); return; default: return; } } catch (Exception ex) { //DisplayAlertError("Something went wrong while using biometric authentication."); } }
private void TakePhoto() { // Get a stable reference of the modifiable image capture use case var imageCapture = this.imageCapture; if (imageCapture == null) { return; } // Create time-stamped output file to hold the image var photoFile = new File(outputDirectory, new Java.Text.SimpleDateFormat(FILENAME_FORMAT, Locale.Us).Format(JavaSystem.CurrentTimeMillis()) + ".jpg"); // Create output options object which contains file + metadata var outputOptions = new ImageCapture.OutputFileOptions.Builder(photoFile).Build(); // Set up image capture listener, which is triggered after photo has been taken imageCapture.TakePicture(outputOptions, ContextCompat.GetMainExecutor(this), new ImageSaveCallback( onErrorCallback: (exc) => { var msg = $"Photo capture failed: {exc.Message}"; Log.Error(TAG, msg, exc); Toast.MakeText(this.BaseContext, msg, ToastLength.Short).Show(); }, onImageSaveCallback: (output) => { var savedUri = output.SavedUri; var msg = $"Photo capture succeeded: {savedUri}"; Log.Debug(TAG, msg); Toast.MakeText(this.BaseContext, msg, ToastLength.Short).Show(); } )); }
private void ShowBiometricPrompt() { var executor = ContextCompat.GetMainExecutor(this); var passwordStorage = new PasswordStorageManager(this); var callback = new AuthenticationCallback(); callback.Success += async(_, result) => { string password; try { password = passwordStorage.Fetch(result.CryptoObject.Cipher); } catch { Toast.MakeText(this, Resource.String.genericError, ToastLength.Short); return; } await AttemptUnlock(password); }; callback.Failed += delegate { FocusPasswordText(); }; callback.Error += (_, result) => { Toast.MakeText(this, result.Message, ToastLength.Short).Show(); FocusPasswordText(); }; _prompt = new BiometricPrompt(this, executor, callback); var promptInfo = new BiometricPrompt.PromptInfo.Builder() .SetTitle(GetString(Resource.String.unlock)) .SetSubtitle(GetString(Resource.String.unlockBiometricsMessage)) .SetNegativeButtonText(GetString(Resource.String.cancel)) .SetConfirmationRequired(false) .SetAllowedAuthenticators(BiometricManager.Authenticators.BiometricStrong) .Build(); Cipher cipher; try { cipher = passwordStorage.GetDecryptionCipher(); } catch { _canUseBiometrics = false; _useBiometricsButton.Enabled = false; return; } _prompt.Authenticate(promptInfo, new BiometricPrompt.CryptoObject(cipher)); }
private void FindAndOpenCamera() { bool cameraPermissions = CheckCameraPermissions(); if (!cameraPermissions) { return; } string errorMessage = "Unknown error"; bool foundCamera = false; IListenableFuture cameraProviderFuture = ProcessCameraProvider.GetInstance(this); cameraProviderFuture.AddListener(new Runnable(() => { // Camera provider is now guaranteed to be available mCameraProvider = cameraProviderFuture.Get() as ProcessCameraProvider; try { // Find first back-facing camera that has necessary capability. CameraSelector cameraSelector = new CameraSelector.Builder().RequireLensFacing((int)mLensFacing).Build(); // Find a good size for output - largest 4:3 aspect ratio that's less than 720p Preview.Builder previewBuilder = new Preview.Builder() .SetTargetAspectRatio(AspectRatio.Ratio43); Camera2Interop.Extender previewExtender = new Camera2Interop.Extender(previewBuilder); previewExtender.SetSessionCaptureCallback(mCaptureCallback); Preview preview = previewBuilder.Build(); // Must unbind the use-cases before rebinding them mCameraProvider.UnbindAll(); ICamera camera = mCameraProvider.BindToLifecycle( this as ILifecycleOwner, cameraSelector, preview); if (camera != null) { // Found suitable camera - get info, open, and set up outputs mCameraInfo = camera.CameraInfo; mCameraControl = camera.CameraControl; preview.SetSurfaceProvider(this); foundCamera = true; } if (!foundCamera) { errorMessage = GetString(Resource.String.camera_no_good); } SwitchRenderMode(0); } catch (CameraAccessException e) { errorMessage = GetErrorString(e); } if (!foundCamera) { ShowErrorDialog(errorMessage); } }), ContextCompat.GetMainExecutor(this)); }
void ViewTreeObserver.IOnGlobalLayoutListener.OnGlobalLayout() { binding !.previewView.ViewTreeObserver !.RemoveOnGlobalLayoutListener(this); cameraProviderFuture !.AddListener(new Runnable(() => { var cameraProvider = (ProcessCameraProvider)cameraProviderFuture.Get() !; BindScan(cameraProvider, binding !.previewView.Width, binding !.previewView.Height); }), ContextCompat.GetMainExecutor(this)); }
private void StartCamera() { var cameraProviderFuture = ProcessCameraProvider.GetInstance(this); cameraProviderFuture.AddListener(new Runnable(() => { _cameraProvider = (ProcessCameraProvider)cameraProviderFuture.Get(); _previewView.PostDelayed(BindCameraUseCases, 16); }), ContextCompat.GetMainExecutor(this)); }
/// <summary> /// https://codelabs.developers.google.com/codelabs/camerax-getting-started#3 /// </summary> private void StartCamera() { var cameraProviderFuture = ProcessCameraProvider.GetInstance(this); cameraProviderFuture.AddListener(new Runnable(() => { // Used to bind the lifecycle of cameras to the lifecycle owner var cameraProvider = (ProcessCameraProvider)cameraProviderFuture.Get(); // Preview var preview = new Preview.Builder().Build(); preview.SetSurfaceProvider(viewFinder.CreateSurfaceProvider()); // Take Photo this.imageCapture = new ImageCapture.Builder().Build(); // Frame by frame analyze var imageAnalyzer = new ImageAnalysis.Builder().Build(); imageAnalyzer.SetAnalyzer(cameraExecutor, new LuminosityAnalyzer(luma => Log.Debug(TAG, $"Average luminosity: {luma}") )); // Select back camera as a default, or front camera otherwise CameraSelector cameraSelector = null; if (cameraProvider.HasCamera(CameraSelector.DefaultBackCamera) == true) { cameraSelector = CameraSelector.DefaultBackCamera; } else if (cameraProvider.HasCamera(CameraSelector.DefaultFrontCamera) == true) { cameraSelector = CameraSelector.DefaultFrontCamera; } else { throw new System.Exception("Camera not found"); } try { // Unbind use cases before rebinding cameraProvider.UnbindAll(); // Bind use cases to camera cameraProvider.BindToLifecycle(this, cameraSelector, preview, imageCapture, imageAnalyzer); } catch (Exception exc) { Log.Debug(TAG, "Use case binding failed", exc); Toast.MakeText(this, $"Use case binding failed: {exc.Message}", ToastLength.Short).Show(); } }), ContextCompat.GetMainExecutor(this)); //GetMainExecutor: returns an Executor that runs on the main thread. }
/// <summary> /// Initializes a new instance of the <see cref="BiometryService" /> class. /// </summary> /// <param name="fragmentActivity"></param> /// <param name="dispatcher"></param> /// <param name="promptInfoBuilder"></param> /// <param name="authenticators"></param> public BiometryService( FragmentActivity fragmentActivity, CoreDispatcher dispatcher, FuncAsync <BiometricPrompt.PromptInfo> promptInfoBuilder) { fragmentActivity.Validation().NotNull(nameof(fragmentActivity)); _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher)); _promptInfoBuilder = promptInfoBuilder ?? throw new ArgumentNullException(nameof(promptInfoBuilder)); _applicationContext = Application.Context; var executor = ContextCompat.GetMainExecutor(_applicationContext); var callback = new AuthenticationCallback(OnAuthenticationSucceeded, OnAuthenticationFailed, OnAuthenticationError); _biometricPrompt = new BiometricPrompt(fragmentActivity, executor, callback); _biometricManager = BiometricManager.From(_applicationContext); _keyStore = KeyStore.GetInstance(ANDROID_KEYSTORE); _keyStore.Load(null); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.activityLogin); var executor = ContextCompat.GetMainExecutor(this); var callback = new AuthenticationCallback(); callback.Success += OnSuccess; callback.Error += OnError; var prompt = new BiometricPrompt(this, executor, callback); var promptInfo = new BiometricPrompt.PromptInfo.Builder() .SetTitle(GetString(Resource.String.login)) .SetSubtitle(GetString(Resource.String.loginMessage)) .SetDeviceCredentialAllowed(true) .Build(); prompt.Authenticate(promptInfo); }
private void ShowBiometicPrompt(IBioAuthCompleted bioAuthCompleted) { var activity = (FragmentActivity)CrossCurrentActivity.Current.Activity; var executor = ContextCompat.GetMainExecutor(activity); var callback = new BiometricAuthenticationCallback { Success = (AndroidX.Biometric.BiometricPrompt.AuthenticationResult result) => { try { bioAuthCompleted.OnCompleted(BioAuthStatus.SUCCESS); } catch (SignatureException) { throw new RuntimeException(); } }, Failed = () => { // TODO: Show error. bioAuthCompleted.OnCompleted(BioAuthStatus.FAILED); }, Help = (BiometricAcquiredStatus helpCode, ICharSequence helpString) => { // TODO: What do we do here? } }; //Create prompt info var promptInfo = new AndroidX.Biometric.BiometricPrompt.PromptInfo.Builder() .SetTitle("Biometric login for my app") .SetSubtitle("Log in using your biometric credential") .SetNegativeButtonText("Use account password") .Build(); //Create prompt var biometricPrompt = new AndroidX.Biometric.BiometricPrompt(activity, executor, callback); //call Authenticate biometricPrompt.Authenticate(promptInfo); }
private BioAuthnPrompt CreateBioAuthnPrompt() { BioAuthnCallback callback = new FidoBioAuthnCallback(); return(new BioAuthnPrompt(this, ContextCompat.GetMainExecutor(this), callback)); }