auth0-swift
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAuth0 Swift Integration
Auth0 Swift 集成
Auth0.swift is the official Auth0 SDK for Apple platforms (iOS, macOS, tvOS, watchOS, visionOS). This skill adds complete native authentication to Swift apps using Web Auth (system browser redirect), secure Keychain credential storage via , and optional biometric protection.
CredentialsManagerAgent instruction: Before providing SDK setup instructions, fetch the latest release version by running:bashgh api repos/auth0/Auth0.swift/releases/latest --jq '.tag_name'Use the returned version in all dependency lines instead of any hardcoded version below. Current known version:.2.18.0
Auth0.swift是Auth0官方推出的适用于Apple平台(iOS、macOS、tvOS、watchOS、visionOS)的SDK。本技能通过Web Auth(系统浏览器重定向)、借助实现的安全Keychain凭证存储,以及可选的生物识别保护,为Swift应用添加完整的原生认证功能。
CredentialsManager**Agent 指令:**在提供SDK设置说明前,请运行以下命令获取最新版本:bashgh api repos/auth0/Auth0.swift/releases/latest --jq '.tag_name'在所有依赖行中使用返回的版本,而非下方任何硬编码版本。当前已知版本:。2.18.0
When NOT to Use
不适用于以下场景
- Android apps: Use auth0-android
- React Native apps: Use auth0-react-native
- Flutter apps: Use the native Flutter Auth0 SDK
- Web SPAs (React, Angular, Vue): Use auth0-react, auth0-angular, or auth0-vue
- Node.js/Express servers: Use auth0-express
- Android应用:使用auth0-android
- React Native应用:使用auth0-react-native
- Flutter应用:使用Flutter原生Auth0 SDK
- Web单页应用(React、Angular、Vue):使用auth0-react、auth0-angular或auth0-vue
- Node.js/Express服务器:使用auth0-express
Prerequisites
前置条件
- iOS 14.0+ / macOS 11.0+ / tvOS 14.0+ / watchOS 7.0+ / visionOS 1.0+
- Xcode 16.x
- Swift 6.0+
- Auth0 account — Sign up free
- Node.js 20+ (for bootstrap script automation)
- Auth0 CLI — (for bootstrap script)
brew install auth0/auth0-cli/auth0
- iOS 14.0+ / macOS 11.0+ / tvOS 14.0+ / watchOS 7.0+ / visionOS 1.0+
- Xcode 16.x
- Swift 6.0+
- Auth0账户 — 免费注册
- Node.js 20+(用于引导脚本自动化)
- Auth0 CLI — (用于引导脚本)
brew install auth0/auth0-cli/auth0
Quick Start Workflow
快速开始流程
Agent instruction: Follow these steps in order. If you encounter an error at any step, attempt to fix it up to 5 times before callingto ask the user for guidance. Always search existing code first — if there are existing login/logout handlers, hook into them rather than creating new ones.AskUserQuestion
**Agent 指令:**按顺序执行以下步骤。若在任意步骤遇到错误,尝试修复最多5次后,再通过向用户寻求指导。请先搜索现有代码——如果已有登录/登出处理程序,请接入现有程序而非创建新程序。AskUserQuestion
Step 1 — Install SDK
步骤1 — 安装SDK
Agent instruction: Check the project directory for an existing package manager file:
present → CocoaPodsPodfile present → CarthageCartfile present → Swift Package ManagerPackage.swiftIf none are found, ask via: "Which dependency manager does your project use — Swift Package Manager, CocoaPods, or Carthage?"AskUserQuestionSwift Package Manager —project: Run this command in the project root to add the dependency automatically, then addPackage.swiftto the target's"Auth0"array independencies:Package.swiftbashswift package add-dependency https://github.com/auth0/Auth0.swift --from 2.18.0Swift Package Manager — Xcode project (, no.xcodeproj): The CLI command does not apply. Instruct the user to add the package via Xcode: File → Add Package Dependencies →Package.swift→ Up to Next Major Version fromhttps://github.com/auth0/Auth0.swift.2.18.0CocoaPods or Carthage: Follow the matching installation steps in Setup Guide. Do not just show the instructions — perform the file edits and run the commands.
**Agent 指令:**检查项目目录中是否存在包管理器文件:
- 存在
→ CocoaPodsPodfile- 存在
→ CarthageCartfile- 存在
→ Swift Package ManagerPackage.swift若均未找到,请通过询问:"您的项目使用哪种依赖管理器——Swift Package Manager、CocoaPods还是Carthage?"AskUserQuestion**Swift Package Manager —项目:**在项目根目录运行以下命令自动添加依赖,然后在Package.swift的目标Package.swift数组中添加dependencies:"Auth0"bashswift package add-dependency https://github.com/auth0/Auth0.swift --from 2.18.0**Swift Package Manager — Xcode项目(,无.xcodeproj):**不适用CLI命令。指导用户通过Xcode添加包:File → Add Package Dependencies →Package.swift→ 从https://github.com/auth0/Auth0.swift开始兼容下一个主版本。2.18.0**CocoaPods或Carthage:**遵循设置指南中的对应安装步骤。请勿仅展示说明——需执行文件编辑并运行命令。
Step 2 — Configure Auth0
步骤2 — 配置Auth0
Agent instruction:
- If Auth0 credentials (domain AND client ID) are already in the user's prompt: Write
directly with those values and proceed to Step 3.Auth0.plist- If no credentials are provided: Run the bootstrap script — do NOT ask the user to create or configure an Auth0 application manually. Always use the CLI path.
Follow Setup Guide — Auth0 Configuration for pre-flight checks and the script command.
Agent 指令:
- **如果用户提示中已提供Auth0凭证(域名和客户端ID):**直接写入
并进入步骤3。Auth0.plist- **如果未提供凭证:**运行引导脚本——请勿让用户手动创建或配置Auth0应用。请始终使用CLI方式。
遵循设置指南 — Auth0配置进行预检和脚本命令操作。
Step 3 — Configure Callback URLs
步骤3 — 配置回调URL
Agent instruction:
- Read
to obtainAuth0.plistandClientId.Domain- Extract the bundle identifier from
: search forproject.pbxproj, skip values containingPRODUCT_BUNDLE_IDENTIFIERor$(.Tests- Ask the user via
: "Which callback URL scheme would you like to use?"AskUserQuestion
- Custom scheme (
) — simpler, works on all Apple platforms{bundle}://- HTTPS Universal Links — recommended for production; prevents URL scheme hijacking
Then follow only the matching path below.
Agent 指令:
- 读取
获取Auth0.plist和ClientId。Domain- 从
中提取Bundle标识符:搜索project.pbxproj,跳过包含PRODUCT_BUNDLE_IDENTIFIER或$(的值。Tests- 通过
询问用户:"您想使用哪种回调URL方案?"AskUserQuestion
- 自定义方案 (
) — 更简单,适用于所有Apple平台{bundle}://- HTTPS通用链接 — 推荐用于生产环境;防止URL方案劫持
然后仅遵循下方对应路径操作。
Path A — Custom Scheme
路径A — 自定义方案
Agent instruction: Register the callback URLs using the Auth0 CLI (substitute real values for,CLIENT_ID,BUNDLE_ID):DOMAINbashauth0 apps update CLIENT_ID \ --callbacks "BUNDLE_ID://DOMAIN/ios/BUNDLE_ID/callback" \ --logout-urls "BUNDLE_ID://DOMAIN/ios/BUNDLE_ID/callback" \ --no-inputThen follow the URL scheme registration steps in Setup Guide to registeras a URL type in Xcode.$(PRODUCT_BUNDLE_IDENTIFIER)
**Agent 指令:**使用Auth0 CLI注册回调URL(将、CLIENT_ID、BUNDLE_ID替换为实际值):DOMAINbashauth0 apps update CLIENT_ID \ --callbacks "BUNDLE_ID://DOMAIN/ios/BUNDLE_ID/callback" \ --logout-urls "BUNDLE_ID://DOMAIN/ios/BUNDLE_ID/callback" \ --no-input然后遵循设置指南中的URL方案注册步骤,在Xcode中注册为URL类型。$(PRODUCT_BUNDLE_IDENTIFIER)
Path B — HTTPS Universal Links
路径B — HTTPS通用链接
Agent instruction: All four steps below are required — skipping any one will cause the callback redirect to fail silently after login.Step B1 — Register callback URLs via Auth0 CLI: Register both HTTPS and custom scheme so the app works in all scenarios:bashauth0 apps update CLIENT_ID \ --callbacks "https://DOMAIN/ios/BUNDLE_ID/callback,BUNDLE_ID://DOMAIN/ios/BUNDLE_ID/callback" \ --logout-urls "https://DOMAIN/ios/BUNDLE_ID/callback,BUNDLE_ID://DOMAIN/ios/BUNDLE_ID/callback" \ --no-inputStep B2 — Configure Device Settings via Auth0 CLI: ExtractfromDEVELOPMENT_TEAM(10-character value, e.g.project.pbxproj). If not found, ask viaABC12DE34F: "What is your Apple Team ID? (developer.apple.com → Account → Membership Details)"AskUserQuestionbashauth0 api patch applications/CLIENT_ID \ --data '{"mobile":{"ios":{"team_id":"TEAM_ID","app_bundle_identifier":"BUNDLE_ID"}}}' \ --no-inputAuth0 will now hostautomatically — required for Universal Links to work on device.https://DOMAIN/.well-known/apple-app-site-associationStep B3 — Add Associated Domains entitlement in Xcode: Addto the app'scom.apple.developer.associated-domainsfile with both.entitlementsandapplinks:entries for the Auth0 domain. See Setup Guide — Associated Domains for the complete entitlements XML, Xcode capability steps, and build settings verification.webcredentials:Step B4 — Usein the SDK:.useHTTPS()swiftAuth0.webAuth().useHTTPS()
**Agent 指令:**以下四个步骤均为必填——跳过任意一步都会导致登录后回调重定向静默失败。步骤B1 — 通过Auth0 CLI注册回调URL: 同时注册HTTPS和自定义方案,确保应用在所有场景下正常工作:bashauth0 apps update CLIENT_ID \ --callbacks "https://DOMAIN/ios/BUNDLE_ID/callback,BUNDLE_ID://DOMAIN/ios/BUNDLE_ID/callback" \ --logout-urls "https://DOMAIN/ios/BUNDLE_ID/callback,BUNDLE_ID://DOMAIN/ios/BUNDLE_ID/callback" \ --no-input步骤B2 — 通过Auth0 CLI配置设备设置: 从中提取project.pbxproj(10位字符值,例如DEVELOPMENT_TEAM)。若未找到,请通过ABC12DE34F询问:"您的Apple团队ID是什么?(developer.apple.com → 账户 → 会员详情)"AskUserQuestionbashauth0 api patch applications/CLIENT_ID \ --data '{"mobile":{"ios":{"team_id":"TEAM_ID","app_bundle_identifier":"BUNDLE_ID"}}}' \ --no-inputAuth0将自动托管——这是通用链接在设备上正常工作的必要条件。https://DOMAIN/.well-known/apple-app-site-association步骤B3 — 在Xcode中添加关联域权限: 将添加到应用的com.apple.developer.associated-domains文件中,并为Auth0域名添加.entitlements和applinks:条目。请查看设置指南 — 关联域获取完整的权限XML、Xcode功能步骤和构建设置验证说明。webcredentials:步骤B4 — 在SDK中使用:.useHTTPS()swiftAuth0.webAuth().useHTTPS()
Step 4 — Implement Authentication
步骤4 — 实现认证功能
Agent instruction: Search the project for(SwiftUI) or@main struct/AppDelegate(UIKit) to detect the UI framework. If ambiguous, ask viaUIViewController: "Does your app use SwiftUI or UIKit?" Then follow only the matching path below.AskUserQuestion
**Agent 指令:**搜索项目中的(SwiftUI)或@main struct/AppDelegate(UIKit)以检测UI框架。若存在歧义,请通过UIViewController询问:"您的应用使用SwiftUI还是UIKit?" 然后仅遵循下方对应路径操作。AskUserQuestion
SwiftUI
SwiftUI
Agent instruction: Createas anAuthenticationService.swift, then wire it into the app entry point and root view. Search for theObservableObjectstruct and@main(or equivalent root view) and update them as shown.ContentView
swift
// AuthenticationService.swift
import Auth0
import Combine
class AuthenticationService: ObservableObject {
@Published var isAuthenticated = false
private let credentialsManager = CredentialsManager(authentication: Auth0.authentication())
init() { isAuthenticated = credentialsManager.canRenew() }
func login() async {
do {
let credentials = try await Auth0
.webAuth()
.useHTTPS()
.scope("openid profile email offline_access")
.start()
_ = credentialsManager.store(credentials: credentials)
await MainActor.run { isAuthenticated = true }
} catch WebAuthError.userCancelled { }
catch { print("Login failed: \(error)") }
}
func logout() async {
do { try await Auth0.webAuth().useHTTPS().clearSession() }
catch { print("Logout failed: \(error)") }
_ = credentialsManager.clear()
await MainActor.run { isAuthenticated = false }
}
}swift
// @main App struct — inject AuthenticationService as environment object
@StateObject private var auth = AuthenticationService()
// In body: ContentView().environmentObject(auth)
// Root ContentView — branch on authentication state
@EnvironmentObject var auth: AuthenticationService
// In body: if auth.isAuthenticated { HomeView() } else { LoginView() }For complete SwiftUI app lifecycle wiring, see Integration Patterns.
**Agent 指令:**创建作为AuthenticationService.swift,然后将其接入应用入口点和根视图。搜索ObservableObject结构体和@main(或等效根视图)并按示例更新。ContentView
swift
// AuthenticationService.swift
import Auth0
import Combine
class AuthenticationService: ObservableObject {
@Published var isAuthenticated = false
private let credentialsManager = CredentialsManager(authentication: Auth0.authentication())
init() { isAuthenticated = credentialsManager.canRenew() }
func login() async {
do {
let credentials = try await Auth0
.webAuth()
.useHTTPS()
.scope("openid profile email offline_access")
.start()
_ = credentialsManager.store(credentials: credentials)
await MainActor.run { isAuthenticated = true }
} catch WebAuthError.userCancelled { }
catch { print("Login failed: \(error)") }
}
func logout() async {
do { try await Auth0.webAuth().useHTTPS().clearSession() }
catch { print("Logout failed: \(error)") }
_ = credentialsManager.clear()
await MainActor.run { isAuthenticated = false }
}
}swift
// @main App结构体 — 将AuthenticationService作为环境对象注入
@StateObject private var auth = AuthenticationService()
// 在body中:ContentView().environmentObject(auth)
// 根ContentView — 根据认证状态分支
@EnvironmentObject var auth: AuthenticationService
// 在body中:if auth.isAuthenticated { HomeView() } else { LoginView() }有关完整的SwiftUI应用生命周期接入,请查看集成模式。
UIKit
UIKit
Agent instruction: Createas a plain class, then add login/logout calls to the relevantAuthenticationService.swift. Also check whether the app usesUIViewController— if so, addSFSafariViewControllertoWebAuthentication.resume(with:)/AppDelegate(see note below).SceneDelegate
swift
// AuthenticationService.swift
import Auth0
class AuthenticationService {
private let credentialsManager = CredentialsManager(authentication: Auth0.authentication())
var isAuthenticated: Bool { credentialsManager.canRenew() }
func login() async throws {
let credentials = try await Auth0
.webAuth()
.useHTTPS()
.scope("openid profile email offline_access")
.start()
_ = credentialsManager.store(credentials: credentials)
}
func logout() async throws {
try await Auth0.webAuth().useHTTPS().clearSession()
_ = credentialsManager.clear()
}
}swift
// In your UIViewController
private let auth = AuthenticationService()
@IBAction func loginTapped(_ sender: UIButton) {
Task {
do {
try await auth.login()
await MainActor.run { navigateToHome() }
} catch WebAuthError.userCancelled { }
catch { print("Login failed: \(error)") }
}
}
@IBAction func logoutTapped(_ sender: UIButton) {
Task {
do { try await auth.logout() }
catch { print("Logout failed: \(error)") }
await MainActor.run { navigateToLogin() }
}
}Note — SFSafariViewController only: If the app usesinstead of the default.provider(WebAuthentication.safariProvider()), addASWebAuthenticationSessiontoWebAuthentication.resume(with: url)andAppDelegate.application(_:open:url:options:). See Integration Patterns for the exact code.SceneDelegate.scene(_:openURLContexts:)
**Agent 指令:**创建作为普通类,然后在相关AuthenticationService.swift中添加登录/登出调用。同时检查应用是否使用UIViewController——如果是,请在SFSafariViewController/AppDelegate中添加SceneDelegate(见下方说明)。WebAuthentication.resume(with:)
swift
// AuthenticationService.swift
import Auth0
class AuthenticationService {
private let credentialsManager = CredentialsManager(authentication: Auth0.authentication())
var isAuthenticated: Bool { credentialsManager.canRenew() }
func login() async throws {
let credentials = try await Auth0
.webAuth()
.useHTTPS()
.scope("openid profile email offline_access")
.start()
_ = credentialsManager.store(credentials: credentials)
}
func logout() async throws {
try await Auth0.webAuth().useHTTPS().clearSession()
_ = credentialsManager.clear()
}
}swift
// 在您的UIViewController中
private let auth = AuthenticationService()
@IBAction func loginTapped(_ sender: UIButton) {
Task {
do {
try await auth.login()
await MainActor.run { navigateToHome() }
} catch WebAuthError.userCancelled { }
catch { print("Login failed: \(error)") }
}
}
@IBAction func logoutTapped(_ sender: UIButton) {
Task {
do { try await auth.logout() }
catch { print("Logout failed: \(error)") }
await MainActor.run { navigateToLogin() }
}
}**说明 — 仅适用于SFSafariViewController:**如果应用使用而非默认的.provider(WebAuthentication.safariProvider()),请在ASWebAuthenticationSession和AppDelegate.application(_:open:url:options:)中添加SceneDelegate.scene(_:openURLContexts:)。请查看集成模式获取确切代码。WebAuthentication.resume(with: url)
Step 5 — Verify Build
步骤5 — 验证构建
Agent instruction: Run a build to verify the integration compiles without errors:bashxcodebuild build -scheme YOUR_SCHEME -destination "platform=iOS Simulator,name=iPhone 16"If the build fails, review error messages and fix up to 5 times before asking the user.
**Agent 指令:**运行构建以验证集成编译无错误:bashxcodebuild build -scheme YOUR_SCHEME -destination "platform=iOS Simulator,name=iPhone 16"如果构建失败,请查看错误信息并尝试修复最多5次后再询问用户。
Detailed Documentation
详细文档
- Setup Guide — Auth0 Dashboard configuration, bootstrap script, manual setup, URL scheme registration, CocoaPods/SPM/Carthage install
- Integration Patterns — Web Auth login/logout, CredentialsManager, biometric protection, MFA, organizations, error handling, SwiftUI/UIKit patterns
- API Reference & Testing — Full API reference, configuration options, claims reference, testing checklist, troubleshooting
- 设置指南 — Auth0控制台配置、引导脚本、手动设置、URL方案注册、CocoaPods/SPM/Carthage安装
- 集成模式 — Web Auth登录/登出、CredentialsManager、生物识别保护、MFA、组织、错误处理、SwiftUI/UIKit模式
- API参考与测试 — 完整API参考、配置选项、声明参考、测试清单、故障排除
Common Mistakes
常见错误
| Mistake | Fix |
|---|---|
| Auth0 app type not set to Native | In Auth0 Dashboard, select "Native" when creating the application |
| Missing callback URL in Auth0 Dashboard | Add both |
| Right-click file in Navigator → "Add Files to Target" → check your app target |
Missing | Add |
Tokens stored in | Always use |
Calling | Store credentials from login result before attempting to retrieve |
Opening | Always open the |
Not calling | Always call |
| Build error "No such module 'Auth0'" | Verify the package is added to the correct target; for CocoaPods, open |
| 错误 | 修复方案 |
|---|---|
| Auth0应用类型未设置为Native | 在Auth0控制台创建应用时选择"Native" |
| Auth0控制台中缺少回调URL | 将 |
| 在导航器中右键点击文件 → "Add Files to Target" → 勾选您的应用目标 |
缺少 | 在权限字符串中添加 |
令牌存储在 | 始终使用 |
在 | 在尝试检索凭证前,先存储登录结果中的凭证 |
打开 | 在 |
登出时未调用 | 始终调用 |
| 构建错误"No such module 'Auth0'" | 验证包已添加到正确目标;对于CocoaPods,请打开 |
Related Skills
相关技能
- - Basic Auth0 setup
auth0-quickstart - - Manage Auth0 resources from the terminal
auth0-cli
- - 基础Auth0设置
auth0-quickstart - - 从终端管理Auth0资源
auth0-cli