PyObjC LocalAuthentication Framework

12.1 · active · verified Tue Apr 14

Wrappers for the framework LocalAuthentication on macOS. This library is part of the larger PyObjC project, a bridge between Python and Objective-C. It allows Python applications to leverage macOS's biometric authentication (Face ID, Touch ID) and passcode features for secure user authentication. Currently at version 12.1, it maintains an active release cadence, typically aligning with macOS SDK updates and Python version support.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `LAContext` to evaluate an authentication policy, typically for biometric authentication (Face ID/Touch ID) or device passcode. It first checks if the policy can be evaluated and then calls `evaluatePolicy_localizedReason_reply_` with a callback function to handle the authentication result. Remember that `pyobjc-framework-localauthentication` is a macOS-only library and requires user interaction via a system prompt.

import objc
from LocalAuthentication import LAContext, LAPolicy

def authenticate_user(reason="Authenticate to access sensitive data."):
    context = LAContext.alloc().init()
    error = objc.nil
    can_evaluate = context.canEvaluatePolicy_error_(LAPolicy.deviceOwnerAuthenticationWithBiometrics, objc.byref(error))

    if not can_evaluate:
        if error is not objc.nil:
            print(f"Biometric authentication not available: {error.localizedDescription()}")
        else:
            print("Biometric authentication not available.")
        # Fallback to device passcode if biometrics not available
        can_evaluate = context.canEvaluatePolicy_error_(LAPolicy.deviceOwnerAuthentication, objc.byref(error))
        if not can_evaluate:
            if error is not objc.nil:
                print(f"Device passcode authentication not available: {error.localizedDescription()}")
            else:
                print("Device passcode authentication not available.")
            return False

    def reply_handler(success, err):
        if success:
            print("Authentication successful!")
        elif err is not objc.nil:
            print(f"Authentication failed: {err.localizedDescription()}")
        else:
            print("Authentication failed (unknown error).")

    context.evaluatePolicy_localizedReason_reply_(LAPolicy.deviceOwnerAuthentication, reason, reply_handler)

# Example usage:
# Note: This will block the Python interpreter until authentication completes or fails.
# In a real GUI app, this would typically be run on a background thread or using a runloop.
authenticate_user()

# To run PyObjC event loop in a console application (optional, for persistent UI/callbacks):
# from PyObjCTools import AppHelper
# AppHelper.runEventLoop() # This should be called if you need to keep a UI or callbacks alive.

view raw JSON →