MCPInstall

authentication

Implement iOS authentication flows with AuthenticationServices and LocalAuthentication. Use when building Sign in with Apple, passkey/WebAuthn registration or sign-in with ASAuthorizationPlatformPublicKeyCredentialProvider, ASAuthorizationController credential state and revocation handling, ASWebAuthenticationSession OAuth or third-party login, Password AutoFill, identity-token server validation, or local biometric re-authentication with LAContext.

Installs
3.9K
Last 24h
+15
Trending rank
#7039
Security
Warn

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/dpearson2699/swift-ios-skills --skill authentication
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads authentication automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

Security audits

Independent scans of the skill's instructions and bundled files.

Gen Agent Trust Hub PassSAFE ·The skill provides instructions and code for implementing iOS authentication flows using AuthenticationServices and LocalAuthentication. It follows security best practices, such as storing tokens in the Keychain and mandating server-side validation of identity tokens. A low-risk surface for indirect prompt injection is identified because the skill processes authentication data and redirect URLs from external providers.
Socket PassNo alerts
Snyk PassLOW ·Risk: LOW · No issues
Runlayer WarnMEDIUM ·2/2 files flagged
ZeroLeaks WarnMEDIUM ·2 findings · Score: 76/100

SKILL.md

The instructions your agent reads when the skill is triggered.

Authentication

Implement authentication flows on iOS using the AuthenticationServices framework, including Sign in with Apple, passkeys, OAuth/third-party web auth, Password AutoFill, and biometric re-authentication.

Contents

Sign in with Apple

Add the "Sign in with Apple" capability in Xcode before using these APIs.

UIKit: ASAuthorizationController Setup

import AuthenticationServices

final class LoginViewController: UIViewController {
    func startSignInWithApple() {
        let provider = ASAuthorizationAppleIDProvider()
        let request = provider.createRequest()
        request.requestedScopes = [.fullName, .email]

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

extension LoginViewController: ASAuthorizationControllerPresentationContextProviding {
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        view.window!
    }
}

Delegate: Handling Success and Failure

extension LoginViewController: ASAuthorizationControllerDelegate {
    func authorizationController(
        controller: ASAuthorizationController,
        didCompleteWithAuthorization authorization: ASAuthorization
    ) {
        guard let credential = authorization.credential
            as? ASAuthorizationAppleIDCredential else { return }

        let userID = credential.user  // Stable, unique, per-team identifier
        let email = credential.email  // nil after first authorization
        let fullName = credential.fullName  // nil after first authorization
        let identityToken = credential.identityToken  // JWT for server validation
        let authCode = credential.authorizationCode  // Short-lived code for server exchange

        // Save userID to Keychain for credential state checks
        // See references/keychain-biometric.md for Keychain patterns
        saveUserID(userID)

        // Send identityToken and authCode to your server
        authenticateWithServer(identityToken: identityToken, authCode: authCode)
    }

    func authorizationController(
        controller: ASAuthorizationController,
        didCompleteWithError error: any Error
    ) {
        switch (error as? ASAuthorizationError)?.code {
        case .canceled, .notInteractive:
            break
        case .failed:
            showError("Authorization failed")
        default:
            showError("Authorization failed: \(error.localizedDescription)")
        }
    }
}

Credential Handling

Credential dataRequired handling
userPersist this stable, per-team identifier for credential-state checks.
email, fullNameThese optional values arrive only on first authorization; cache them immediately.
identityToken, authorizationCodeSend them to the server for validation or exchange; never trust them as client-side proof.

Treat realUserStatus only as a fraud-prevention signal, not authentication proof.

Credential State Checking

Check credential state on every app launch. The user may revoke access at any time via Settings > Apple Account > Sign-In & Security.

func checkCredentialState() {
    let provider = ASAuthorizationAppleIDProvider()
    guard let userID = loadSavedUserID() else {
        showLoginScreen()
        return
    }

    provider.getCredentialState(forUserID: userID) { state, _ in
        DispatchQueue.main.async {
            switch state {
            case .authorized:
                proceedToMainApp()
            case .revoked:
                // User revoked -- sign out and clear local data
                signOut()
                showLoginScreen()
            case .notFound:
                showLoginScreen()
            case .transferred:
                // App transferred to new team -- migrate user identifier
                migrateUser()
            @unknown default:
                showLoginScreen()
            }
        }
    }
}

Credential Revocation Notification

NotificationCenter.default.addObserver(
    forName: ASAuthorizationAppleIDProvider.credentialRevokedNotification,
    object: nil,
    queue: .main
) { _ in
    // Sign out immediately
    AuthManager.shared.signOut()
}

Token Validation

The identityToken is a JWT. Send it to your server for validation -- never trust it client-side alone.

Server-side, validate the JWT against Apple's public keys at https://appleid.apple.com/auth/keys (JWKS). Verify: iss is https://appleid.apple.com, aud matches your bundle ID, and exp has not passed. Exchange the short-lived authorization code on the server and store the resulting app session token in Keychain.

Existing Account Setup Flows

On launch, silently check for existing Sign in with Apple and password credentials before showing a login screen:

func performExistingAccountSetupFlows() {
    let appleIDRequest = ASAuthorizationAppleIDProvider().createRequest()
    let passwordRequest = ASAuthorizationPasswordProvider().createRequest()

    let controller = ASAuthorizationController(
        authorizationRequests: [appleIDRequest, passwordRequest]
    )
    controller.delegate = self
    controller.presentationContextProvider = self
    controller.performRequests(
        options: .preferImmediatelyAvailableCredentials
    )
}

Call this in viewDidAppear or on app launch. If no existing credentials are found, the delegate receives a .notInteractive error -- handle it silently and show your normal login UI.

Passkeys

Use passkeys only for a relying-party domain configured with a webcredentials: Associated Domain and AASA entry. Registration and assertion each require a fresh server challenge, an ASAuthorizationPlatformPublicKeyCredentialProvider, an authorization controller with an active presentation anchor, and server-side verification before issuing a session.

Load references/passkeys.md for the canonical registration, assertion, result handling, AutoFill-assisted, and physical security-key flows.

ASWebAuthenticationSession (OAuth)

Use ASWebAuthenticationSession for OAuth and third-party authentication (Google, GitHub, etc.). Never use WKWebView for auth flows.

import AuthenticationServices

final class OAuthController: NSObject, ASWebAuthenticationPresentationContextProviding {
    private weak var presentationAnchor: ASPresentationAnchor?

    init(presentationAnchor: ASPresentationAnchor) {
        self.presentationAnchor = presentationAnchor
    }

    func startOAuthFlow() {
        let authURL = URL(string:
            "https://provider.com/oauth/authorize?client_id=YOUR_ID&redirect_uri=myapp://callback&response_type=code"
        )!
        let session = ASWebAuthenticationSession(
            url: authURL, callback: .customScheme("myapp")
        ) { callbackURL, error in
            guard let callbackURL, error == nil,
                  let code = URLComponents(url: callbackURL, resolvingAgainstBaseURL: false)?
                      .queryItems?.first(where: { $0.name == "code" })?.value else { return }
            Task { await self.exchangeCodeForTokens(code) }
        }
        session.presentationContextProvider = self
        session.prefersEphemeralWebBrowserSession = true  // No shared cookies
        session.start()
    }

    func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
        guard let presentationAnchor else {
            fatalError("ASWebAuthenticationSession needs the active window")
        }
        return presentationAnchor
    }
}

In SwiftUI, use @Environment(\.webAuthenticationSession) and call authenticate(using:callback:preferredBrowserSession:additionalHeaderFields:) with .customScheme("myapp") or .https(host:path:); prefer .ephemeral only when the provider flow should avoid shared browser cookies.

Password AutoFill Credentials

Offer ASAuthorizationPasswordProvider alongside Sign in with Apple using the single controller in Existing Account Setup Flows. Handle ASPasswordCredential in that controller's delegate.

Set textContentType on text fields for AutoFill to work:

usernameField.textContentType = .username
passwordField.textContentType = .password

Biometric Authentication

Use LAContext from LocalAuthentication for local re-authentication before showing account settings or starting sensitive actions. Do not treat a returned Bool as proof to unlock a stored secret; protect secrets with Keychain access control instead. See references/keychain-biometric.md for the canonical LAContext, fallback, SecAccessControl, and .biometryCurrentSet patterns.

Required: Add NSFaceIDUsageDescription to Info.plist. Missing this key crashes on Face ID devices.

Security Boundaries

This skill owns user-facing account authentication: Sign in with Apple, passkeys, Password AutoFill, ASAuthorizationController, OAuth session presentation, credential state, and local biometric re-authentication. Route deep security work to swift-security: Keychain architecture/migration, CryptoKit, Secure Enclave, certificate pinning/trust, keychain sharing, storage hardening, and OWASP MASVS/MASTG. Keep only the storage minimum here: tokens and secrets belong in Keychain; LAContext.evaluatePolicy alone must not release protected secrets.

SwiftUI SignInWithAppleButton

Use SignInWithAppleButton in SwiftUI views when the login surface is SwiftUI. Request .fullName and .email, downcast a successful result to ASAuthorizationAppleIDCredential, and pass it to the shared Token Validation flow. Style with .signInWithAppleButtonStyle(...).

Common Mistakes

  • Assuming a saved local session means the Apple ID credential is still valid. Check credential state at launch and handle revocation notifications.
  • Showing a full login screen before trying existing account setup flows. Treat .notInteractive as the normal "no local credential" path.
  • Force-unwrapping email or fullName. Cache them on first authorization and handle nil later.
  • Creating an ASAuthorizationController without a presentation context provider. Authorization UI needs the active presentation anchor.
  • Storing identity tokens, authorization codes, access tokens, passwords, or passkey server state in UserDefaults, files, or Core Data. Store secrets in Keychain and keep relying-party passkey verification server-side.
  • Adding passkey requests without webcredentials: Associated Domains for the relying-party domain, or trying to use app-native passkeys for unrelated websites.
  • Expanding authentication work into CryptoKit, Secure Enclave, certificate pinning, or OWASP MASVS. Route those to swift-security.

Review Checklist

  • "Sign in with Apple" capability added in Xcode project
  • ASAuthorizationControllerPresentationContextProviding implemented
  • Credential state checked on every app launch (getCredentialState(forUserID:completion:))
  • credentialRevokedNotification observer registered; sign-out handled
  • email and fullName cached on first authorization (not assumed available later)
  • identityToken sent to server for validation, not trusted client-side only
  • Tokens stored in Keychain, not UserDefaults or files
  • performExistingAccountSetupFlows called before showing login UI
  • Error cases handled: .canceled, .failed, .notInteractive
  • NSFaceIDUsageDescription in Info.plist for biometric auth
  • ASWebAuthenticationSession used for OAuth (not WKWebView)
  • prefersEphemeralWebBrowserSession set for OAuth when appropriate
  • textContentType set on username/password fields for AutoFill
  • Passkey relying party has webcredentials: Associated Domains configured
  • Passkey registration/assertion challenges come from the server and are verified server-side
  • Deep Keychain, CryptoKit, Secure Enclave, certificate pinning, and MASVS work routed to swift-security

References

FAQ

What does the authentication skill do?

Implement iOS authentication flows with AuthenticationServices and LocalAuthentication. Use when building Sign in with Apple, passkey/WebAuthn registration or sign-in with ASAuthorizationPlatformPublicKeyCredentialProvider, ASAuthorizationController credential state and revocation handling, ASWebAuthenticationSession OAuth or third-party login, Password AutoFill, identity-token server validation, or local biometric re-authentication with LAContext.

How do I install authentication?

Run npx skills add https://github.com/dpearson2699/swift-ios-skills --skill authentication in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/authentication/ (personal) or .claude/skills/authentication/ (project).

Which AI agents can use authentication?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is authentication safe to install?

Security partners have reviewed it: Gen Agent Trust Hub passed; Socket passed; Snyk passed; Runlayer flagged items to review; ZeroLeaks flagged items to review. As with any skill, read the SKILL.md and bundled scripts before installing.

Who maintains authentication?

It is published by dpearson2699 in dpearson2699/swift-ios-skills. It has 3,900 recorded installs.

More from dpearson2699/swift-ios-skills

View all →

swiftui-animation

dpearson2699/swift-ios-skills

Implement, diagnose, or review SwiftUI motion using explicit and scoped implicit animations, springs, transitions, PhaseAnimator, KeyframeAnimator, matched geometry or navigation zoom, SF Symbol effects, and custom Animation types. Use when views should animate on state changes, insertion, removal, navigation, or multi-step choreography, or when motion must respect Reduce Motion and Swift concurrency.

Mobile5.5K installs

ios-accessibility

dpearson2699/swift-ios-skills

Build and audit SwiftUI, UIKit, and AppKit accessibility for VoiceOver, Voice Control, Switch Control, Full Keyboard Access, Dynamic Type, focus restoration, labels/traits/actions, traversal, custom rotors, NSAccessibility, XCTest checks, adaptive system preferences, and App Store accessibility declarations. Use when implementing accessible UI, fixing an accessibility audit, testing assistive-technology behavior, or substantiating App Store Accessibility Nutrition Labels.

Mobile5K installs

swiftui-performance

dpearson2699/swift-ios-skills

Profile, diagnose, and remediate SwiftUI runtime performance using code review, Instruments, and repeatable measurements. Use when a SwiftUI screen renders slowly, scrolling or animations hitch, view bodies update excessively, list identity churns, layout work spikes, or broad Observation dependencies raise CPU cost. Covers evidence-based triage, SwiftUI Instruments lanes, lazy-container guardrails, state lifetime, and before/after verification.

Mobile4.6K installs

swiftui-patterns

dpearson2699/swift-ios-skills

Builds and reviews SwiftUI views with modern MV architecture, state, composition, isolated previews, and migration guidance. Covers @Observable ownership, @State/@Bindable/@Environment wiring, view decomposition, ViewModifiers, environment values, .task loading, iOS 26+ handoffs, Writing Tools, clipboard availability, and performance. Use when structuring SwiftUI state, managing @Observable, composing views, previewing meaningful UI states, or correcting SwiftUI patterns.

Mobile4.6K installs

app-store-review

dpearson2699/swift-ios-skills

Audits App Store submission readiness and rejection risk across current review guidelines, PrivacyInfo.xcprivacy and required-reason APIs, privacy labels, ATT, StoreKit payments, metadata, entitlements, widgets, and Live Activities. Use when preparing a submission, responding to rejection, reconciling privacy evidence, or separating upload blockers from cleanup.

Mobile4.6K installs

ios-networking

dpearson2699/swift-ios-skills

Build, review, or improve networking code in iOS/macOS apps using URLSession with async/await, structured concurrency, and modern Swift patterns. Use when working with REST APIs, downloading files, uploading data, WebSocket connections, pagination, retry logic, request middleware, caching, background transfers, or network reachability monitoring. Also use when handling HTTP requests, API clients, network error handling, or data fetching in Swift apps.

Mobile4.4K installs

Popular mobile skills

View category →

design-mobile-apps

designed-by-ai/skills

Design mobile app screens with Sleek, edit Sleek projects, and implement their designs in React Native or HTML.

Mobile1.1M installs

ios-design

uizze.sh

Design and review iOS UI/UX for iPhone apps in SwiftUI, UIKit, or React Native. Use for mobile app design, screen redesigns, navigation flows, typography, forms, keyboard and safe-area layout, and accessibility checks. Apply Apple Human Interface Guidelines and consult real product references through the optional Uizze connection.

Mobile416.5K installs

vercel-react-native-skills

vercel-labs/agent-skills

React Native and Expo best practices for building performant mobile apps. Use when building React Native components, optimizing list performance, implementing animations, or working with native modules. Triggers on tasks involving React Native, Expo, mobile performance, or native platform APIs.

OfficialMobile256.7K installs

animate-expo

emilkowalski/skills

Build animations in React Native and Expo, making the decisions in the order that determines whether they feel right — should it animate, which thread it runs on, which properties, spring or timing, how the gesture hands off, how it degrades. Writes the implementation with Reanimated, Gesture Handler, Expo Router and expo-haptics. Use when animating anything in an Expo app, adding gestures, sheets, screen transitions, press feedback or haptics, or fixing motion that stutters on device. For web animation use animate.

Mobile140.1K installs

xcode-project-setup

firebase/agent-skills

Safely modifies Xcode projects (.pbxproj) to add Swift Packages and link files. Use this skill whenever an iOS project needs dependencies installed (e.g. Firebase, Alamofire).

OfficialMobile131.2K installs

firebase-remote-config-basics

firebase/agent-skills

Manages Firebase Remote Config templates, feature flags, loading strategies, and SDKs (Android, iOS). Use when downloading/deploying remoteconfig JSON templates, managing version history/feature flags, setting in-app defaults, fetchAndActivate(), real-time listeners, or SDK setup. Don't use for Firebase Hosting, Auth, Firestore, Data Connect, Crashlytics, or App Hosting.

OfficialMobile121.7K installs