您可以让您的用户使用 GitHub 等 OAuth 提供商通过 Firebase 进行身份验证,方法是使用 Firebase SDK 将通用 OAuth 登录集成到您的应用程序中以执行端到端登录流程。
在你开始之前
要使用 GitHub 帐户登录用户,您必须首先启用 GitHub 作为您的 Firebase 项目的登录提供商:
使用 Swift Package Manager 安装和管理 Firebase 依赖项。
- 在 Xcode 中,打开您的应用程序项目,导航至File > Add Packages 。
- 出现提示时,添加 Firebase Apple 平台 SDK 存储库:
- 选择 Firebase 身份验证库。
- 完成后,Xcode 将自动开始在后台解析和下载您的依赖项。
https://github.com/firebase/firebase-ios-sdk
现在,执行一些配置步骤:
- 在Firebase 控制台中,打开Auth部分。
- 在登录方法选项卡上,启用GitHub提供程序。
- 将该提供商的开发人员控制台中的客户端 ID和客户端密码添加到提供商配置中:
- 在 GitHub 上将您的应用程序注册为开发人员应用程序,并获取您应用程序的 OAuth 2.0 Client ID和Client Secret 。
- 确保您的 Firebase OAuth 重定向 URI (例如
my-app-12345.firebaseapp.com/__/auth/handler
)在您的GitHub 应用程序配置页面中设置为您的授权回调 URL 。
- 单击保存。
使用 Firebase SDK 处理登录流程
要使用 Firebase Apple 平台 SDK 处理登录流程,请执行以下步骤:
将自定义 URL 方案添加到您的 Xcode 项目:
- 打开您的项目配置:双击左侧树视图中的项目名称。从TARGETS部分选择您的应用程序,然后选择Info选项卡,并展开URL Types部分。
- 单击+按钮,并为您的反向客户端 ID 添加 URL 方案。要查找此值,请打开
配置文件,然后查找GoogleService-Info.plist REVERSED_CLIENT_ID
键。复制该键的值,并将其粘贴到配置页面上的URL Schemes框中。将其他字段留空。完成后,您的配置应类似于以下内容(但具有特定于应用程序的值):
使用提供者 ID github.com创建OAuthProvider的实例。
迅速
var provider = OAuthProvider(providerID: "github.com")
目标-C
FIROAuthProvider *provider = [FIROAuthProvider providerWithProviderID:@"github.com"];
可选:指定要与 OAuth 请求一起发送的其他自定义 OAuth 参数。
迅速
provider.customParameters = [ "allow_signup": "false" ]
目标-C
[provider setCustomParameters:@{@"allow_signup": @"false"}];
GitHub 支持的参数参见GitHub OAuth 文档。请注意,您不能使用
setCustomParameters
传递 Firebase 所需的参数。这些参数是client_id 、 redirect_uri 、 response_type 、 scope和state 。可选:指定要从身份验证提供程序请求的基本配置文件之外的其他 OAuth 2.0 范围。如果您的应用程序需要从 GitHub API 访问私人用户数据,您需要在 GitHub 开发人员控制台的API 权限下请求访问 GitHub API 的权限。请求的 OAuth 范围必须与应用程序 API 权限中的预配置范围完全匹配。
迅速
// Request read access to a user's email addresses. // This must be preconfigured in the app's API permissions. provider.scopes = ["user:email"]
目标-C
// Request read access to a user's email addresses. // This must be preconfigured in the app's API permissions. [provider setScopes:@[@"user:email"]];
要了解更多信息,请参阅GitHub 范围文档。
可选:如果您想在向用户显示 reCAPTCHA 时自定义您的应用程序呈现
SFSafariViewController
或UIWebView
的方式,请创建一个符合AuthUIDelegate
协议的自定义类,并将其传递给credentialWithUIDelegate
。使用 OAuth 提供程序对象通过 Firebase 进行身份验证。
迅速
provider.getCredentialWith(nil) { credential, error in if error != nil { // Handle error. } if credential != nil { Auth().signIn(with: credential) { authResult, error in if error != nil { // Handle error. } // User is signed in. // IdP data available in authResult.additionalUserInfo.profile. guard let oauthCredential = authResult.credential as? OAuthCredential else { return } // GitHub OAuth access token can also be retrieved by: // oauthCredential.accessToken // GitHub OAuth ID token can be retrieved by calling: // oauthCredential.idToken } } }
目标-C
[provider getCredentialWithUIDelegate:nil completion:^(FIRAuthCredential *_Nullable credential, NSError *_Nullable error) { if (error) { // Handle error. } if (credential) { [[FIRAuth auth] signInWithCredential:credential completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) { if (error) { // Handle error. } // User is signed in. // IdP data available in authResult.additionalUserInfo.profile. FIROAuthCredential *oauthCredential = (FIROAuthCredential *)authResult.credential; // GitHub OAuth access token can also be retrieved by: // oauthCredential.accessToken // GitHub OAuth ID token can be retrieved by calling: // oauthCredential.idToken }]; } }];
使用 OAuth 访问令牌,您可以调用GitHub API 。
例如,要获取基本的个人资料信息,您可以调用 REST API,在
Authorization
标头中传递访问令牌:https://api.github.com/user
虽然上述示例侧重于登录流程,但您也可以将 GitHub 提供商链接到现有用户。例如,您可以将多个提供商链接到同一个用户,允许他们使用其中任何一个登录。
迅速
Auth().currentUser.link(withCredential: credential) { authResult, error in if error != nil { // Handle error. } // GitHub credential is linked to the current user. // IdP data available in authResult.additionalUserInfo.profile. // GitHub OAuth access token can also be retrieved by: // (authResult.credential as? OAuthCredential)?.accessToken // GitHub OAuth ID token can be retrieved by calling: // (authResult.credential as? OAuthCredential)?.idToken }
目标-C
[[FIRAuth auth].currentUser linkWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { if (error) { // Handle error. } // GitHub credential is linked to the current user. // IdP data available in authResult.additionalUserInfo.profile. // GitHub OAuth access token is can also be retrieved by: // ((FIROAuthCredential *)authResult.credential).accessToken // GitHub OAuth ID token can be retrieved by calling: // ((FIROAuthCredential *)authResult.credential).idToken }];
相同的模式可以与
reauthenticateWithCredential
一起使用,它可用于为需要最近登录的敏感操作检索新的凭据。迅速
Auth().currentUser.reauthenticateWithCredential(withCredential: credential) { authResult, error in if error != nil { // Handle error. } // User is re-authenticated with fresh tokens minted and // should be able to perform sensitive operations like account // deletion and email or password update. // IdP data available in result.additionalUserInfo.profile. // Additional OAuth access token is can also be retrieved by: // (authResult.credential as? OAuthCredential)?.accessToken // GitHub OAuth ID token can be retrieved by calling: // (authResult.credential as? OAuthCredential)?.idToken }
目标-C
[[FIRAuth auth].currentUser reauthenticateWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { if (error) { // Handle error. } // User is re-authenticated with fresh tokens minted and // should be able to perform sensitive operations like account // deletion and email or password update. // IdP data available in result.additionalUserInfo.profile. // Additional OAuth access token is can also be retrieved by: // ((FIROAuthCredential *)authResult.credential).accessToken // GitHub OAuth ID token can be retrieved by calling: // ((FIROAuthCredential *)authResult.credential).idToken }];
下一步
用户首次登录后,将创建一个新的用户帐户并将其链接到用户登录所用的凭据,即用户名和密码、电话号码或身份验证提供商信息。这个新帐户存储为您的 Firebase 项目的一部分,可用于在项目中的每个应用程序中识别用户,无论用户如何登录。
在您的 Firebase Realtime Database 和 Cloud Storage Security Rules中,您可以从
auth
变量中获取登录用户的唯一用户 ID,并使用它来控制用户可以访问的数据。
您可以允许用户使用多个身份验证提供程序登录您的应用程序,方法是将身份验证提供程序凭据链接到现有用户帐户。
要注销用户,请调用signOut:
。
迅速
let firebaseAuth = Auth.auth() do { try firebaseAuth.signOut() } catch let signOutError as NSError { print("Error signing out: %@", signOutError) }
目标-C
NSError *signOutError; BOOL status = [[FIRAuth auth] signOut:&signOutError]; if (!status) { NSLog(@"Error signing out: %@", signOutError); return; }
您可能还想为所有身份验证错误添加错误处理代码。请参阅处理错误。