PyObjC AuthenticationServices Framework

12.1 · active · verified Tue Apr 14

PyObjC is a bridge between Python and Objective-C, enabling Python developers to write full-featured macOS Cocoa applications. The `pyobjc-framework-authenticationservices` package provides Python wrappers for the macOS `AuthenticationServices` framework. It is currently at version 12.1 and follows the release cadence of the broader PyObjC project, typically releasing new versions to align with macOS SDK updates and Python version support changes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initiate a web authentication session using `ASWebAuthenticationSession` from the `AuthenticationServices` framework. It sets up a minimal `NSApplication` and defines a delegate to handle the authentication session's completion, failure, or cancellation, which are crucial for interactive macOS frameworks. The `presentationAnchorForWebAuthenticationSession_` method provides the necessary display context for the authentication UI.

import objc
from AppKit import NSApplication, NSApp, NSWindow, NSApplicationActivationPolicyRegular
from Foundation import NSObject, NSURL, NSError
from AuthenticationServices import (
    ASWebAuthenticationSession,
    ASWebAuthenticationSessionDelegate,
    ASWebAuthenticationPresentationContextProviding,
)
import os

# Define a delegate for ASWebAuthenticationSession and its presentation context
class WebAuthSessionDelegate(
    NSObject,
    ASWebAuthenticationSessionDelegate,
    ASWebAuthenticationPresentationContextProviding,
):
    def init(self):
        self = objc.super(WebAuthSessionDelegate, self).init()
        return self

    # Required ASWebAuthenticationSessionDelegate methods
    def authenticationSession_didCompleteWithCallbackURL_(self, session, callbackURL):
        print(f"Authentication session completed with URL: {callbackURL.absoluteString()}")
        NSApp.terminate_(None)

    def authenticationSession_didFailWithError_(self, session, error):
        print(f"Authentication session failed with error: {error.localizedDescription()}")
        NSApp.terminate_(None)

    def authenticationSession_didCancel_(self, session):
        print("Authentication session cancelled.")
        NSApp.terminate_(None)

    # Required ASWebAuthenticationPresentationContextProviding method
    def presentationAnchorForWebAuthenticationSession_(self, session):
        # In a real GUI app, this would return the main window of your application.
        # For a minimal example, we'll try to get the key window or create a dummy one.
        # Note: The application needs to be activated for a window to be meaningfully presented.
        if NSApp.keyWindow():
            return NSApp.keyWindow()
        else:
            # Fallback for headless environments or early stages; may not always work perfectly
            # Create a minimal, temporary window if no key window is available.
            # This might not be suitable for all presentation contexts.
            window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(((0,0),(1,1)), 0, 0, False)
            window.makeKeyAndOrderFront_(None)
            return window

def main():
    # Establish a shared NSApplication instance
    if not NSApp:
        _ = NSApplication.sharedApplication()
    NSApp.setActivationPolicy_(NSApplicationActivationPolicyRegular)

    delegate_instance = WebAuthSessionDelegate.alloc().init()

    # Dummy URLs for demonstration purposes
    auth_url = NSURL.URLWithString_("https://www.example.com/auth")
    callback_scheme = "myapp" # e.g., 'myapp://callback'

    # Create the authentication session
    session = ASWebAuthenticationSession.alloc().initWithURL_callbackURLScheme_completionHandler_(
        auth_url,
        callback_scheme,
        None # We use the delegate methods for completion/failure
    )

    # Set the delegate for both completion and presentation context
    session.setDelegate_(delegate_instance)
    session.setPresentationContextProvider_(delegate_instance)

    # Start the session
    print("Starting ASWebAuthenticationSession...")
    if not session.start():
        print("Failed to start ASWebAuthenticationSession.")
        NSApp.terminate_(None)

    # Run the application event loop until terminated by the delegate
    NSApp.run()

if __name__ == "__main__":
    main()

view raw JSON →