PyObjC AuthenticationServices Framework
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
- breaking PyObjC 12.0 dropped support for Python 3.9. Users must upgrade to Python 3.10 or later.
- breaking PyObjC 11.0 dropped support for Python 3.8. Users must upgrade to Python 3.9 or later (though 3.10+ is recommended for 12.x).
- gotcha PyObjC 11.1 introduced alignment with clang's Automatic Reference Counting (ARC) documentation for `init` methods. Specifically, methods in the 'init' family now correctly model that they steal a reference to `self` and return a new reference. Code relying on previous, potentially incorrect, reference counting behavior for `init` methods might need adjustment.
- gotcha In PyObjC 10.3, a change briefly broke the ability to use `__init__` in Python subclasses when `__new__` was also custom-implemented (either in the class or a superclass). This was re-enabled in 10.3.1. However, if relying on the `__new__` provided by PyObjC, `__init__` cannot be used.
- breaking PyObjC 10.0 dropped support for Python 3.7. Users must upgrade to Python 3.8 or later (though newer versions are recommended for current PyObjC releases).
Install
-
pip install pyobjc-framework-authenticationservices
Imports
- AuthenticationServices
import AuthenticationServices
- ASWebAuthenticationSession
from AuthenticationServices import ASWebAuthenticationSession
- NSApplication
from AppKit import NSApplication
Quickstart
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()