OAuth 客户端 for Swift (iOS/macOS):OAuthSwift 库
OAuthSwift 是一个强大且灵活的库,用于在 iOS、macOS、watchOS 和 tvOS 的 Swift 应用中实现 OAuth 1.0 和 OAuth 2.0 协议。它为开发者提供了一个简单直观的接口,用于集成第三方服务(如 Google、GitHub、Facebook、Twitter 等),无需手动处理复杂的 HTTP 请求、重定向和令牌交换。该库完全用 Swift 编写,支持现代语言版本(Swift 5+),并得到社区的积极维护。
OAuthSwift 的主要优势在于最大限度地减少了样板代码。开发者只需提供客户端 ID (client ID)、客户端密钥 (client secret)、授权和重定向 URL 地址,库本身即可管理获取访问令牌的过程。OAuthSwift 支持所有常见的 OAuth 2.0 授权类型:授权码、隐式、客户端凭证和资源所有者密码凭证。对于 OAuth 1.0,它完全支持 HMAC-SHA1、RSA-SHA1 和 Plaintext 签名方法。
安装与集成
该库通过 Swift Package Manager (SPM)、CocoaPods 和 Carthage 分发。推荐使用 SPM:
// 在 Xcode 中:File → Swift Packages → Add Package Dependency// URL:https://github.com/OAuthSwift/OAuthSwift.git// 版本:2.2.0 及以上在代码中导入:
import OAuthSwiftOAuth 2.0 基本实现(以 Google 为例)
让我们看一个使用授权码流程通过 Google 进行授权的完整示例。首先,需要在 Google Cloud Console 中创建一个项目,获取客户端 ID,并配置重定向 URI(例如,com.example.app:/oauth-callback)。
class GoogleAuthManager { private var oauthSwift: OAuth2Swift?
func startGoogleAuth() { oauthSwift = OAuth2Swift( consumerKey: "YOUR_CLIENT_ID", consumerSecret: "YOUR_CLIENT_SECRET", authorizeUrl: "https://accounts.google.com/o/oauth2/auth", accessTokenUrl: "https://oauth2.googleapis.com/token", responseType: "code" )
// 配置请求参数 let state = generateState(withLength: 20) let scope = "https://www.googleapis.com/auth/userinfo.profile"
// 启动授权 oauthSwift?.authorize( withCallbackURL: URL(string: "com.example.app:/oauth-callback")!, scope: scope, state: state, parameters: [:], headers: nil ) { result in switch result { case .success(let (credential, response, parameters)): print("访问令牌:\\(credential.oauthToken)") print("刷新令牌:\\(credential.oauthRefreshToken)") self.fetchUserInfo(credential: credential) case .failure(let error): print("授权错误:\\(error.localizedDescription)") } } }
private func fetchUserInfo(credential: OAuthSwiftCredential) { let url = "https://www.googleapis.com/oauth2/v2/userinfo" oauthSwift?.client.get(url, parameters: [:]) { result in switch result { case .success(let response): if let json = try? JSONSerialization.jsonObject(with: response.data) as? [String: Any] { print("邮箱:\\(json["email"] ?? "")") print("姓名:\\(json["name"] ?? "")") } case .failure(let error): print("获取数据错误:\\(error)") } } }}处理 URL 方案 (iOS)
为了正确运行回调 URL,需要配置 AppDelegate 或 SceneDelegate:
// AppDelegate.swiftfunc applic