dpearson2699/authentification

Implémentez des flux d'authentification iOS avec AuthenticationServices et LocalAuthentication. Utilisez-le pour créer une connexion avec Apple, l'enregistrement ou la connexion par passkey/WebAuthn avec ASAuthorizationPlatformPublicKeyCredentialProvider, la gestion de l'état des credentials et de la révocation avec ASAuthorizationController, les connexions OAuth ou tierces avec ASWebAuthenticationSession, le remplissage automatique de mots de passe, la validation côté serveur des jetons d'identité, ou la ré-authentification biométrique locale avec LAContext.

Qu'est-ce que authentification ?

Le skill dpearson2699/authentification fournit un guide complet pour implémenter des flux d'authentification iOS robustes en utilisant les frameworks AuthenticationServices et LocalAuthentication d'Apple. Il couvre un large éventail de scénarios, notamment la connexion avec Apple, l'enregistrement et la connexion via passkey (WebAuthn) avec ASAuthorizationPlatformPublicKeyCredentialProvider, la gestion des états et de la révocation des credentials via ASAuthorizationController (y compris la gestion des notifications asynchrones comme les changements de mot de passe iCloud), les connexions OAuth ou tierces avec ASWebAuthenticationSession (en gérant correctement la session web et la redirection), le remplissage automatique de mots de passe (avec les configurations de type de texte de champ), et la validation côté serveur des jetons d'identité. Il inclut également la ré-authentification biométrique locale avec LAContext, en détaillant comment évaluer les politiques, gérer les erreurs LAError et configurer les options de contrôle d'accès. Ce skill est utile pour les développeurs iOS qui souhaitent intégrer des mécanismes d'authentification modernes et sécurisés dans leurs applications, en respectant les meilleures pratiques d'Apple. Il est conçu pour être utilisé avec des agents de codage comme Claude Code, Cursor ou Codex, et fournit des instructions claires et structurées pour chaque étape de l'implémentation, y compris la configuration des entitlements et la gestion des appels asynchrones.

Compatible avec~Claude Code~Codex CLI~Cursor
Part ofMobile
npx skills add https://github.com/dpearson2699/swift-ios-skills/tree/main/skills/authentication

Installed? Explore more Développement et programmation skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Demander à votre IA préférée

Ouvre une nouvelle conversation avec cette compétence d'agent déjà préchargée.

Documentation

Que fait authentification ?

Implémentez des flux d'authentification iOS avec AuthenticationServices et LocalAuthentication. Utilisez-le pour créer une connexion avec Apple, l'enregistrement ou la connexion par passkey/WebAuthn avec ASAuthorizationPlatformPublicKeyCredentialProvider, la gestion de l'état des credentials et de la révocation avec ASAuthorizationController, les connexions OAuth ou tierces avec ASWebAuthenticationSession, le remplissage automatique de mots de passe, la validation côté serveur des jetons d'identité, ou la ré-authentification biométrique locale avec LAContext.

Exigences

  • iOS 15.0+ (requis pour ASAuthorizationPlatformPublicKeyCredentialProvider)
  • Xcode 14+
  • Entitlements : com.apple.developer.authentication-services.autorevoke (pour la gestion de la révocation)
  • Entitlements : com.apple.developer.applesignin (pour la connexion avec Apple)
  • Info.plist : NSFaceIDUsageDescription (pour Face ID)

Utilisation et exemples de code

1. Connexion avec Apple

import AuthenticationServices

let appleIDProvider = ASAuthorizationAppleIDProvider()
let request = appleIDProvider.createRequest()
request.requestedScopes = [.fullName, .email]

let controller = ASAuthorizationController(authorizationRequests: [request])
controller.delegate = self
controller.presentationContextProvider = self
controller.performRequests()

// Gérer les résultats dans le délégué :
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
    if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
        let userIdentifier = appleIDCredential.user
        let fullName = appleIDCredential.fullName
        let email = appleIDCredential.email
        let identityToken = appleIDCredential.identityToken
        let authorizationCode = appleIDCredential.authorizationCode
        // Envoyer identityToken et authorizationCode à votre serveur pour validation
    }
}

func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
    // Gérer l'erreur
}

2. Passkey / WebAuthn

// Créer un fournisseur pour les passkeys
let platformProvider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: "example.com")

// Enregistrement
let registrationRequest = platformProvider.createCredentialRegistrationRequest(challenge: challengeData, name: "[email protected]", userID: userIDData)

// Connexion
let assertionRequest = platformProvider.createCredentialAssertionRequest(challenge: challengeData)

let controller = ASAuthorizationController(authorizationRequests: [registrationRequest])
controller.delegate = self
controller.performRequests()

// Vérifier les résultats :
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
    if #available(iOS 15.0, *) {
        if let credentialRegistration = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialRegistration {
            // Stocker credentialID et le credential côté serveur
        } else if let credentialAssertion = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion {
            // Vérifier la signature avec credentialID et le credential côté serveur
        }
    }
}

3. Gestion de l'état des credentials et de la révocation

import AuthenticationServices

// Surveiller les changements d'état des credentials
let appleIDProvider = ASAuthorizationAppleIDProvider()

// Vérifier l'état d'un identifiant utilisateur (par exemple, au lancement de l'application)
appleIDProvider.getCredentialState(forUserID: "votre-identifiant-utilisateur-stocké") { (credentialState, error) in
    switch credentialState {
    case .authorized:
        // L'identifiant utilisateur est toujours valide
    case .revoked:
        // L'utilisateur s'est déconnecté de l'application
        // Supprimer les données utilisateur locales et rediriger vers l'écran de connexion
    case .notFound:
        // L'identifiant utilisateur n'existe pas
        // Dans ce cas, traiter comme une nouvelle inscription
    default:
        break
    }
}

// S'abonner aux notifications de révocation (nécessite l'entitlement com.apple.developer.authentication-services.autorevoke)
// L'application recevra des notifications lorsque les credentials sont révoqués de manière asynchrone

4. Connexion OAuth / tierce avec ASWebAuthenticationSession

import AuthenticationServices

class AuthManager: NSObject, ASWebAuthenticationPresentationContextProviding {
    
    var webAuthSession: ASWebAuthenticationSession?
    
    func startOAuthFlow() {
        guard let authURL = URL(string: "https://example.com/oauth/authorize?client_id=YOUR_CLIENT_ID&redirect_uri=yourapp://callback&response_type=code&scope=openid%20profile") else { return }
        
        let callbackURLScheme = "yourapp"
        
        webAuthSession = ASWebAuthenticationSession(url: authURL, callbackURLScheme: callbackURLScheme) { callbackURL, error in
            guard error == nil, let callbackURL = callbackURL else {
                // Gérer l'erreur
                return
            }
            
            // Extraire le code d'autorisation de l'URL de callback
            // URL typique : yourapp://callback?code=AUTHORIZATION_CODE&state=STATE
            let queryItems = URLComponents(url: callbackURL, resolvingAgainstBaseURL: false)?.queryItems
            let authorizationCode = queryItems?.filter({ $0.name == "code" }).first?.value
            
            // Échanger le code d'autorisation contre des jetons via une requête réseau
        }
        
        webAuthSession?.presentationContextProvider = self
        webAuthSession?.prefersEphemeralWebBrowserSession = true  // Utiliser un navigateur privé
        webAuthSession?.start()
    }
    
    func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
        return UIApplication.shared.windows.first ?? ASPresentationAnchor()
    }
}

5. Remplissage automatique de mots de passe

// Configurer les champs de texte dans votre vue pour le remplissage automatique :
let usernameTextField = UITextField()
usernameTextField.textContentType = .username

let passwordTextField = UITextField()
passwordTextField.textContentType = .password

// Pour la connexion, configurer le type de contenu du formulaire :
// Dans votre ViewController ou votre vue, associer les champs
// Le remplissage automatique iOS gérera l'affichage des suggestions de mots de passe

// Pour un nouveau compte :
let newPasswordTextField = UITextField()
newPasswordTextField.textContentType = .newPassword

// Activer le partage de mots de passe avec les credentials associés

6. Validation côté serveur des jetons d'identité

// Envoyer le jeton d'identité du côté client au serveur pour validation
// Le jeton provient d'ASAuthorizationAppleIDCredential.identityToken
func sendIdentityTokenToServer(identityToken: Data, authorizationCode: Data) {
    // Convertir les données en chaîne base64
    let identityTokenString = identityToken.base64EncodedString()
    let authorizationCodeString = authorizationCode.base64EncodedString()
    
    let parameters: [String: Any] = [
        "identity_token": identityTokenString,
        "authorization_code": authorizationCodeString,
        "user_id": "votre-identifiant-utilisateur-stocké"
    ]
    
    // Effectuer une requête POST vers votre serveur
    // Le serveur doit valider le jeton d'identité JWT en utilisant la clé publique d'Apple
    // et échanger le code d'autorisation contre des jetons de rafraîchissement si nécessaire
}

7. Ré-authentification biométrique locale avec LAContext

import LocalAuthentication

func authenticateWithBiometrics() {
    let context = LAContext()
    var error: NSError?
    
    // Configurer la politique d'évaluation
    context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error)
    
    if let error = error {
        // Gérer l'erreur (par exemple, Face ID non disponible)
        return
    }
    
    let reason = "Authentifiez-vous pour accéder à vos données sécurisées"
    context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { success, evaluateError in
        DispatchQueue.main.async {
            if success {
                // Authentification réussie, procéder à l'action sécurisée
            } else {
                // Gérer l'erreur d'authentification (par exemple, tentative annulée)
                if let laError = evaluateError as? LAError {
                    switch laError.code {
                    case .userCancel:
                        // L'utilisateur a annulé
                    case .authenticationFailed:
                        // Échec de l'authentification
                    case .userFallback:
                        // L'utilisateur a choisi d'utiliser un mot de passe (fallback)
                    default:
                        break
                    }
                }
            }
        }
    }
    
    // Pour une politique plus flexible (biométrie OU code d'accès) :
    // context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason) { success, error in ... }
}

// Configurer les options de contrôle d'accès pour un élément de trousseau :
let accessControl = SecAccessControlCreateWithFlags(nil,
    kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,
    .userPresence,  // Nécessite la présence de l'utilisateur (biométrie ou code d'accès)
    nil)

// Utiliser ce contrôle d'accès lors de l'ajout d'éléments au trousseau

Meilleures pratiques

  • Mécanismes de secours : Implémentez toujours des mécanismes de secours pour les cas d'absence de biométrie ou d'échec.
  • File d'attente principale : effectuez les mises à jour de l'interface utilisateur dans les rappels d'évaluation sur la file d'attente principale.
  • Gestion des erreurs : gérez les erreurs LAError pour chaque cas d'échec (annulation par l'utilisateur, échec d'authentification, secours, etc.).
  • Jetons d'identité : validez toujours les jetons d'identité côté serveur ; ne faites jamais confiance aux jetons reçus du client sans vérification.
  • Révocation : gérez correctement la révocation des credentials en supprimant les données utilisateur locales et en déconnectant l'utilisateur.
  • Passkeys : utilisez ASAuthorizationPlatformPublicKeyCredentialProvider uniquement pour iOS 15.0+. Assurez-vous que votre serveur prend en charge WebAuthn.
  • ASWebAuthenticationSession : préférez prefersEphemeralWebBrowserSession = true pour éviter de partager des cookies avec Safari, sauf si l'application a besoin de les conserver.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

dpearson2699/accessorysetupkit

Discover and configure Bluetooth and Wi-Fi accessories using AccessorySetupKit. Use when presenting a privacy-preserving accessory picker, defining discovery descriptors for BLE or Wi-Fi devices, handling accessory session events, migrating from CoreBluetooth permission-based scanning, or setting up accessories without requiring broad Bluetooth permissions.

dpearson2699/activitykit

Implement, review, or improve Live Activities and Dynamic Island experiences in iOS apps using ActivityKit. Use when building real-time updating widgets for the Lock Screen and Dynamic Island — delivery tracking, sports scores, ride-sharing status, workout timers, media playback, or any time-sensitive information that updates in real time. Also use when working with ActivityKit, ActivityAttributes, Activity lifecycle (request/update/end), Dynamic Island layouts (compact/minimal/expanded), push-to-update Live Activities, or Lock Screen live widgets.

dpearson2699/adattributionkit

Measure ad effectiveness with privacy-preserving attribution using AdAttributionKit. Use when registering ad impressions, handling attribution postbacks, updating conversion values, implementing re-engagement attribution, configuring publisher or advertiser apps, or replacing SKAdNetwork with AdAttributionKit for ad measurement.

dpearson2699/alarmkit

Implement AlarmKit alarms and countdown timers for iOS and iPadOS with Lock Screen, Dynamic Island, and Apple Watch system UI. Covers AlarmManager scheduling, AlarmAttributes and AlarmPresentation, AlarmButton stop and snooze actions, authorization, state observation, and Live Activity integration. Use when building wake-up alarms, countdown timers, or alarm-style alerts that need Apple's system alarm experience.

dpearson2699/app-clips

Build iOS App Clips with invocation URLs, App Clip Codes, NFC, QR codes, Safari banners, Maps, Messages, target setup, App Store Connect experiences, size/capability constraints, NSUserActivity routing, SKOverlay promotion, App Group/keychain handoff, ephemeral notifications, location confirmation, and full-app migration. Use when creating App Clips or wiring App Clip invocation, experience configuration, or full-app handoff.

dpearson2699/app-intents

Implement App Intents for Siri, Shortcuts, Spotlight, widgets, Control Center, and Apple Intelligence on iOS. Covers AppIntent actions, AppEntity and EntityQuery models, AppShortcutsProvider phrases, IndexedEntity Spotlight indexing, WidgetConfigurationIntent, SnippetIntent, and assistant schemas. Use when exposing app actions or entities to system surfaces.

dpearson2699/apple-on-device-ai

Integrate on-device AI using Foundation Models framework, Core ML, and open-source LLM runtimes on Apple Silicon. Covers Foundation Models (LanguageModelSession, @Generable, @Guide, SystemLanguageModel, structured output, tool calling), Core ML (coremltools, model conversion, quantization, palettization, pruning, Neural Engine, MLTensor), MLX Swift (transformer inference, unified memory), and llama.cpp (GGUF, cross-platform LLM). Use when building tool-calling AI features, working with guided generation schemas, converting models, or running on-device inference.

dpearson2699/appmigrationkit

Transfer app data to or from other platforms using AppMigrationKit. Use when implementing system-orchestrated one-time migration between iOS and Android or another platform, building an AppMigrationExtension, packaging transportable resources with ResourcesArchiver, importing resources on the destination device, reporting import progress, handling migration errors and app group cleanup, checking MigrationStatus, or testing migration code with AppMigrationTester.

dpearson2699/app-store-review

Prepare for App Store review and prevent rejections. Covers App Store review guidelines, app rejection reasons, PrivacyInfo.xcprivacy privacy manifest requirements, required API reason codes, in-app purchase IAP and StoreKit rules, App Store Guidelines compliance, ATT App Tracking Transparency, EU DMA Digital Markets Act, HIG compliance checklist, app submission preparation, review preparation, metadata requirements, entitlements, widgets, and Live Activities review rules. Use when preparing for App Store submission, fixing rejection reasons, auditing privacy manifests, implementing ATT consent flow, configuring StoreKit IAP, or checking HIG compliance.

dpearson2699/audioaccessorykit

Support audio accessory features like automatic switching using AudioAccessoryKit. Use when implementing automatic audio routing for paired accessories, registering audio accessory configuration from the container app, updating placement or connected audio source identifiers from an app extension, or handling AccessoryControlDevice capabilities and errors.

dpearson2699/avkit

Create media playback experiences using AVKit. Use when adding video players with AVPlayerViewController, enabling Picture-in-Picture, routing media with AirPlay, using SwiftUI VideoPlayer views, configuring transport controls, displaying subtitles and closed captions, or integrating AVFoundation playback with system UI.

dpearson2699/background-processing

Schedule and execute background work on iOS using BGTaskScheduler. Use when registering BGAppRefreshTask for short background fetches, BGProcessingTask for long-running maintenance, BGContinuedProcessingTask (iOS 26+) for foreground-started work that continues in background, background URLSession downloads, or background push notifications. Covers Info.plist configuration, expiration handling, task completion, and debugging with simulated launches.

dpearson2699/browserenginekit

Build alternative browser engines using BrowserEngineKit. Use when developing a non-WebKit browser engine for iOS/iPadOS in supported regions, managing web content/rendering/networking extension processes, configuring GPU and networking process capabilities, checking alternative-engine device eligibility, or reviewing BrowserEngineKit entitlements and Info.plist setup.

dpearson2699/callkit

Implement VoIP calling with CallKit and PushKit. Use when building incoming/outgoing call flows, registering for VoIP push notifications, configuring CXProvider and CXCallController, handling call actions, coordinating audio sessions, or creating Call Directory extensions for caller ID and call blocking.

dpearson2699/carplay

Build CarPlay-enabled apps using the CarPlay framework. Use when creating navigation, audio, communication, EV charging, parking, or food ordering apps for the car display, working with CPTemplateApplicationScene, CPInterfaceController template hierarchies, CPListTemplate, CPMapTemplate, CPNowPlayingTemplate, configuring CarPlay entitlements, or integrating with CarPlay Simulator for testing.

dpearson2699/cloudkit

Implement, review, or improve CloudKit and iCloud sync in iOS/macOS apps. Use when working with CKContainer, CKRecord, CKQuery, CKSubscription, CKSyncEngine, CKShare, NSUbiquitousKeyValueStore, or iCloud Drive file coordination; when syncing SwiftData models via ModelConfiguration with cloudKitDatabase; when handling CKError codes for conflict resolution, network failures, or quota limits; or when checking iCloud account status before performing sync operations.

dpearson2699/contacts-framework

Read, create, update, and pick contacts using the Contacts and ContactsUI frameworks. Use when fetching contact data, saving new contacts, wrapping CNContactPickerViewController in SwiftUI, handling contact permissions, or working with CNContactStore fetch and save requests.

dpearson2699/core-bluetooth

Build direct Bluetooth Low Energy workflows with Core Bluetooth. Use when implementing BLE central or peripheral GATT communication, scanning or connecting with CBCentralManager, discovering services and characteristics, reading/writing/subscribing with CBPeripheral, publishing local services with CBPeripheralManager, handling Bluetooth authorization, background BLE modes, state restoration, write flow control, or CBUUID-based workflows. For privacy-preserving accessory setup/picker flows, use accessorysetupkit first and return here for post-setup GATT communication.

dpearson2699/coreml

Integrate Core ML models in iOS apps for on-device machine learning inference. Covers model loading (.mlmodel, .mlpackage, .mlmodelc), predictions with auto-generated classes and MLFeatureProvider, compute unit configuration (CPU, GPU, Neural Engine), MLTensor, VNCoreMLRequest, MLComputePlan, multi-model pipelines, and deployment strategies. Use when loading Core ML models, making predictions, configuring compute units, or profiling model performance.

dpearson2699/core-motion

Access Core Motion accelerometer, gyroscope, magnetometer, device-motion, pedometer, activity-recognition, altitude, headphone motion, batched high-frequency workout motion, and water-submersion/depth data. Use when reading device sensors, counting steps, detecting walking/running/driving/cycling, tracking altitude, building motion interactions, handling AirPods head tracking, or implementing watchOS dive/depth features.

Skills associés