用 Swift 编写的极简 Google 登录 oAuth 2.0 客户端
GoogleSignIn-Swift 兼容 Swift Package Manager。您可以按照官方文档将其作为依赖项添加到您的 Xcode 项目。
您需要配置 Google oAuth 2.0 客户端
在您的项目中创建 GoogleSignIn.Controller 实例
import GoogleSignIn
let controller = GoogleSignIn.Controller(
config: GoogleSignIn.Config(
clientId: "CLIENT_ID",
clientSecret: "CLIENT_SECRET",
redirectUri: "REDIRECT_URI"
),
session: URLSession.shared
)
您可以从 Google API 控制台 获取 CLIENT_ID 和 CLIENT_SECRET。
REDIRECT_URI 是您的 CLIENT_ID,采用反向域名表示法,并带有 :// 后缀。例如
1234-abcd.apps.googleusercontent.comcom.googleusercontent.apps.1234-abcdcom.googleusercontent.apps.1234-abcd://通过打开控制器提供的 signInPageURL,实现向用户展示登录页面。
这可能会因您正在使用的应用程序类型而异。 在 iOS 应用中,最简单的方法是使用 UIApplication.open(_ url:)
UIApplication.shared.open(controller.signInPageURL)
配置您的应用程序,使其可以处理登录后的重定向。
对于 iOS 应用程序,您可以通过在 Info.plist 中添加或修改 CFBundleURLTypes 来完成此操作
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string></string>
<key>CFBundleURLSchemes</key>
<array>
<string>REDIRECT_URI_SCHEME</string>
</array>
</dict>
</array>
使用反向域名表示法将 REDIRECT_URI_SCHEME 替换为您的 CLIENT_ID。 例如:com.googleusercontent.apps.1234-abcd。
处理用户登录后的重定向,通过在 GoogleSignIn.Controller 上调用 getTokenResponse 函数来获取 oAuth 令牌(访问令牌、ID 令牌和刷新令牌)。
对于 iOS 应用程序,您可以通过在 UIApplicationDelegate 中实现此函数来完成此操作
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
controller.getTokenResponse(using: url) { result in
if case let .success(response) = result {
print("ACCESS TOKEN: \(response.accessToken)")
}
}
return true
}
如果在您的应用程序中使用 UIWindowSceneDelegate,请改为实现此函数
func scene(_ scene: UIScene, openURLContexts contexts: Set<UIOpenURLContext>) {
guard let redirectUrl = contexts.first?.url else { return }
controller.getTokenResponse(using: redirectUrl) { result in
if case let .success(response) = result {
print("ACCESS TOKEN: \(response.accessToken)")
}
}
}
使用获得的访问令牌做任何你想做的事情。
版权所有 © 2019 Dariusz Rybicki Darrarski
许可证:GNU GPLv3