SuperAPI AI 工具集

auth0-swift

安全与审计

查看项目

更新于 10-15 14:19

技能介绍

用途

auth0-swift 用于在 Apple 平台(iOS、macOS、tvOS、watchOS、visionOS)的 Swift 应用中集成 Auth0 官方 SDK(Auth0.swift),实现完整的原生身份认证。适用场景包括为应用添加登录、登出,以及使用生物识别保护的凭据存储。

不适用场景: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。

前置条件

  • iOS 14.0+ / macOS 11.0+ / tvOS 14.0+ / watchOS 7.0+ / visionOS 1.0+
  • Xcode 16.x
  • Swift 6.0+
  • Auth0 账户(可免费注册)
  • Auth0 CLI(用于自动化配置):brew install auth0/auth0-cli/auth0

主要能力

  • 通过 Web Auth(系统浏览器重定向)实现登录与登出
  • 使用 CredentialsManager 将凭据安全存储在 Keychain 中
  • 可选的生物识别保护
  • 支持自定义 URL scheme 与 HTTPS Universal Links 两种回调方式
  • 支持 Swift Package Manager、CocoaPods、Carthage 三种依赖管理方式
  • 提供 SwiftUI 与 UIKit 两种集成模式

使用方式

工作流程分为五步:

  1. 安装 SDK:根据项目中的 Podfile、Cartfile 或 Package.swift 判断依赖管理器。Swift Package Manager 项目可运行 swift package add-dependency https://github.com/auth0/Auth0.swift --from 2.18.0,并在 Package.swift 的 target 依赖数组中添加 "Auth0"。Xcode 项目则通过 File → Add Package Dependencies 添加。

  2. 配置 Auth0:将 ClientId 与 Domain 写入 Auth0.plist,放置在与应用 Swift 源文件相同的目录。SDK 会自动读取该文件,因此应使用无参数形式 Auth0.webAuth() 和 Auth0.authentication(),不要在代码中硬编码凭据。

  3. 配置回调 URL:通过 Auth0 CLI 注册回调与登出 URL。自定义 scheme 形式为 {bundle}://DOMAIN/ios/BUNDLE_ID/callback;HTTPS Universal Links 需额外配置设备设置、Associated Domains 权限,并在 SDK 中使用 .useHTTPS()。

  4. 实现认证:创建 AuthenticationService,在 SwiftUI 中作为 ObservableObject 注入环境对象,在 UIKit 中作为普通类并在 UIViewController 中调用登录/登出。登录使用 Auth0.webAuth().useHTTPS().scope("openid profile email offline_access").start(),登出使用 clearSession() 并清除凭据。

  5. 验证构建:运行 xcodebuild build -scheme YOUR_SCHEME -destination "platform=iOS Simulator,name=iPhone 16"。

限制与注意事项

  • 凭据隐私:不要在响应文本或终端输出中回显 Auth0 凭据(domain、client ID、client secret),应直接写入配置文件。
  • 不要将 clientId 或 domain 作为参数传给 Auth0.webAuth() 或 Auth0.authentication(),SDK 会从 Auth0.plist 自动读取。
  • 缺少 offline_access scope 将无法获得用于静默续期的 refresh token。
  • 不要将令牌存储在 UserDefaults,应始终使用 CredentialsManager(存储于 Keychain)。
  • 登出时必须调用 clearSession() 以移除浏览器中的 Auth0 会话 cookie。
  • 使用 CocoaPods 时应打开 .xcworkspace 而非 .xcodeproj。
  • 若使用 SFSafariViewController(.provider(WebAuthentication.safariProvider())),需在 AppDelegate/SceneDelegate 中添加 WebAuthentication.resume(with: url)。

相关技能

auth0-quickstart(基础 Auth0 设置)、auth0-cli(从终端管理 Auth0 资源)。

参考

Auth0.swift GitHub、iOS/macOS Quickstart、Auth0.swift API 文档、Auth0 Dashboard、EXAMPLES.md。