Token导航 LogoToken导航TokenDH.com
开发敏感数据github未标认证来源可访问许可证需确认审计提醒

authentication身份认证

Agent Skill

用于辅助安全审计、权限检查、凭据风险、认证流程和常见漏洞排查。它适合让 Agent 梳理敏感配置、检查依赖风险、分析鉴权逻辑或生成安全复核清单。使用时不能把工具输出直接当最终结论,涉及密钥、令牌、用户数据或生产系统时,应先确认最小权限、脱敏方式和操作边界。

总安装

26,280

周安装

1,068

GitHub Stars

506

下载量

9,140
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:authentication(身份认证)
来源仓库:https://github.com/dpearson2699/swift-ios-skills
仓库路径:skills/authentication
安装命令:
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill authentication
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

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

简介

authentication 指导在 iOS 应用中集成 Sign in with Apple、OAuth 与生物识别认证。

  • 适用于需要安全登录、第三方授权或多因素验证的移动应用开发项目。
  • 涵盖 ASAuthorizationController、ASWebAuthenticationSession 等核心 API 使用方法。
  • 涉及用户隐私数据,必须正确处理凭证存储与传输加密,防止泄露风险。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

Authentication

Implement authentication flows on iOS using the AuthenticationServices framework, including Sign in with Apple, OAuth/third-party web auth, Password AutoFill, and biometric 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
    ) {
        let authError = error as? ASAuthorizationError
        switch authError?.code {
        case .canceled:
            break  // User dismissed
        case .failed:
            showError("Authorization failed")
        case .invalidResponse:
            showError("Invalid response")
        case .notHandled:
            showError("Not handled")
        case .notInteractive:
            break  // Non-interactive request failed -- expected for silent checks
        default:
            showError("Unknown error")
        }
    }
}

Credential Handling

ASAuthorizationAppleIDCredential properties and their behavior:

PropertyTypeFirst AuthSubsequent Auth
userStringAlwaysAlways
emailString?Provided if requestednil
fullNamePersonNameComponents?Provided if requestednil
identityTokenData?JWT (Base64)JWT (Base64)
authorizationCodeData?Short-lived codeShort-lived code
realUserStatusASUserDetectionStatus.likelyReal / .unknown.unknown

Critical: email and fullName are provided ONLY on the first authorization. Cache them immediately during the initial sign-up flow. If the user later deletes and re-adds the app, these values will not be returned.

func handleCredential(_ credential: ASAuthorizationAppleIDCredential) {
    // Always persist the user identifier
    let userID = credential.user

    // Cache name and email IMMEDIATELY -- only available on first auth
    if let fullName = credential.fullName {
        let name = PersonNameComponentsFormatter().string(from: fullName)
        UserProfile.saveName(name)  // Persist to your backend
    }
    if let email = credential.email {
        UserProfile.saveEmail(email)  // Persist to your backend
    }
}

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() async {
    let provider = ASAuthorizationAppleIDProvider()
    guard let userID = loadSavedUserID() else {
        showLoginScreen()
        return
    }

    do {
        let state = try await provider.credentialState(forUserID: userID)
        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()
        }
    } catch {
        // Network error -- allow offline access or retry
        proceedToMainApp()
    }
}

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.

func sendTokenToServer(credential: ASAuthorizationAppleIDCredential) async throws {
    guard let tokenData = credential.identityToken,
          let token = String(data: tokenData, encoding: .utf8),
          let authCodeData = credential.authorizationCode,
          let authCode = String(data: authCodeData, encoding: .utf8) else {
        throw AuthError.missingToken
    }

    var request = URLRequest(url: URL(string: "https://api.example.com/auth/apple")!)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = try JSONEncoder().encode(
        ["identityToken": token, "authorizationCode": authCode]
    )

    let (data, response) = try await URLSession.shared.data(for: request)
    guard (response as? HTTPURLResponse)?.statusCode == 200 else {
        throw AuthError.serverValidationFailed
    }
    let session = try JSONDecoder().decode(SessionResponse.self, from: data)
    // Store session token in Keychain -- see references/keychain-biometric.md
    try KeychainHelper.save(session.accessToken, forKey: "accessToken")
}

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, exp not passed.

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.

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 {
    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 {
        ASPresentationAnchor()
    }
}

SwiftUI WebAuthenticationSession

struct OAuthLoginView: View {
    @Environment(\.webAuthenticationSession) private var webAuthSession

    var body: some View {
        Button("Sign in with Provider") {
            Task {
                let url = URL(string: "https://provider.com/oauth/authorize?client_id=YOUR_ID")!
                let callbackURL = try await webAuthSession.authenticate(
                    using: url, callback: .customScheme("myapp")
                )
                // Extract authorization code from callbackURL
            }
        }
    }
}

Callback types: .customScheme("myapp") for URL scheme redirects; .https(host:path:) for universal link redirects (preferred).

Password AutoFill Credentials

Use ASAuthorizationPasswordProvider to offer saved keychain credentials alongside Sign in with Apple:

func performSignIn() {
    let appleIDRequest = ASAuthorizationAppleIDProvider().createRequest()
    appleIDRequest.requestedScopes = [.fullName, .email]

    let passwordRequest = ASAuthorizationPasswordProvider().createRequest()

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

// In delegate:
func authorizationController(
    controller: ASAuthorizationController,
    didCompleteWithAuthorization authorization: ASAuthorization
) {
    switch authorization.credential {
    case let appleIDCredential as ASAuthorizationAppleIDCredential:
        handleAppleIDLogin(appleIDCredential)
    case let passwordCredential as ASPasswordCredential:
        // User selected a saved password from keychain
        signInWithPassword(
            username: passwordCredential.user,
            password: passwordCredential.password
        )
    default:
        break
    }
}

Set textContentType on text fields for AutoFill to work:

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

Biometric Authentication

Use LAContext from LocalAuthentication for Face ID / Touch ID as a sign-in or re-authentication mechanism. For protecting Keychain items with biometric access control (SecAccessControl, .biometryCurrentSet), see the swift-security skill.

import LocalAuthentication

func authenticateWithBiometrics() async throws -> Bool {
    let context = LAContext()
    var error: NSError?

    guard context.canEvaluatePolicy(
        .deviceOwnerAuthenticationWithBiometrics, error: &error
    ) else {
        throw AuthError.biometricsUnavailable
    }

    return try await context.evaluatePolicy(
        .deviceOwnerAuthenticationWithBiometrics,
        localizedReason: "Sign in to your account"
    )
}

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

SwiftUI SignInWithAppleButton

import AuthenticationServices

struct AppleSignInView: View {
    @Environment(\.colorScheme) var colorScheme

    var body: some View {
        SignInWithAppleButton(.signIn) { request in
            request.requestedScopes = [.fullName, .email]
        } onCompletion: { result in
            switch result {
            case .success(let authorization):
                guard let credential = authorization.credential
                    as? ASAuthorizationAppleIDCredential else { return }
                handleCredential(credential)
            case .failure(let error):
                handleError(error)
            }
        }
        .signInWithAppleButtonStyle(
            colorScheme == .dark ? .white : .black
        )
        .frame(height: 50)
    }
}

Common Mistakes

1. Not checking credential state on app launch

// DON'T: Assume the user is still authorized
func appDidLaunch() {
    if UserDefaults.standard.bool(forKey: "isLoggedIn") {
        showMainApp()  // User may have revoked access!
    }
}

// DO: Check credential state every launch
func appDidLaunch() async {
    await checkCredentialState()  // See "Credential State Checking" above
}

2. Not performing existing account setup flows

// DON'T: Always show a full login screen on launch
// DO: Call performExistingAccountSetupFlows() first;
//     show login UI only if .notInteractive error received

3. Assuming email/name are always provided

// DON'T: Force-unwrap email or fullName
let email = credential.email!  // Crashes on subsequent logins

// DO: Handle nil gracefully -- only available on first authorization
if let email = credential.email {
    saveEmail(email)  // Persist immediately
}

4. Not implementing ASAuthorizationControllerPresentationContextProviding

// DON'T: Skip the presentation context provider
controller.delegate = self
controller.performRequests()  // May not display UI correctly

// DO: Always set the presentation context provider
controller.delegate = self
controller.presentationContextProvider = self  // Required for proper UI
controller.performRequests()

5. Storing identityToken in UserDefaults

// DON'T: Store tokens in UserDefaults
UserDefaults.standard.set(tokenString, forKey: "identityToken")

// DO: Store in Keychain
// See references/keychain-biometric.md for Keychain patterns
try KeychainHelper.save(tokenData, forKey: "identityToken")

Review Checklist

  • "Sign in with Apple" capability added in Xcode project
  • ASAuthorizationControllerPresentationContextProviding implemented
  • Credential state checked on every app launch (credentialState(forUserID:))
  • 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

References

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

37.81%
按下载量换算3,456

Claude

28.52%
按下载量换算2,607

Cursor

17.23%
按下载量换算1,575

Gemini CLI

9.12%
按下载量换算834

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

可疑

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills