如果您已升級至 Firebase Authentication with Identity Platform,可以使用符合 OpenID Connect (OIDC) 規範的提供者,透過 Firebase 驗證使用者。這樣一來,您就能使用 Firebase 原生不支援的識別資訊提供者。
事前準備
如要使用 OIDC 供應商登入使用者,您必須先從供應商收集一些資訊:
用戶端 ID:供應商專屬的字串,用於識別您的應用程式。供應商可能會為您支援的每個平台指派不同的用戶端 ID。這是供應商核發的 ID 權杖中
aud宣告的其中一個值。用戶端密鑰:提供者用來確認用戶端 ID 擁有權的密鑰字串。每個用戶端 ID 都必須有相符的用戶端密鑰。 (只有在使用授權碼流程時,才需要提供這個值,強烈建議您使用這個流程)。
Issuer:用於識別供應商的字串。這個值必須是網址,附加
/.well-known/openid-configuration後,即為供應商 OIDC 導覽文件的位置。舉例來說,如果核發者是https://auth.example.com,則導覽文件必須位於https://auth.example.com/.well-known/openid-configuration。
取得上述資訊後,請為 Firebase 專案啟用 OpenID Connect 做為登入程序提供者:
如果尚未升級至 Firebase Authentication with Identity Platform,請先升級。只有升級後的專案才能使用 OpenID Connect 驗證。
在 Firebase 控制台中,依序前往「Security」(安全性) >「Authentication」(驗證)。
在「Sign-in method」(登入方式) 分頁中,依序點選「Add new provider」(新增供應商) 和「OpenID Connect」。
選取要使用授權碼流程或隱含授權流程。
如果供應商支援授權碼流程,請一律使用該流程。隱含流程的安全性較低,強烈建議不要使用。
為這個供應商命名。記下系統產生的提供者 ID,例如
oidc.example-provider。在應用程式中加入登入程式碼時,您需要這個 ID。指定用戶端 ID、用戶端密鑰和供應商的核發者字串。這些值必須與供應商指派給你的值完全一致。
儲存變更。
使用 Firebase SDK 處理登入流程
如要使用 OIDC 供應商透過 Firebase 驗證使用者,最簡單的方法是使用 Firebase SDK 處理整個登入流程。
如要使用 Firebase Apple 平台 SDK 處理登入流程,請按照下列步驟操作:
在 Xcode 專案中新增自訂網址配置:
- 開啟專案設定:在左側樹狀檢視中,按兩下專案名稱。在「TARGETS」部分選取應用程式,然後選取「Info」分頁標籤,並展開「URL Types」部分。
-
按一下「+」按鈕,然後將編碼應用程式 ID 新增為網址配置。
其他欄位則留空。
您可以在 Firebase 控制台中找到編碼應用程式 ID:依序前往「
Settings 」>「General」分頁,然後向下捲動至「Your apps」部分,查看 iOS 應用程式的詳細資料。完成後,設定應如下所示 (但包含應用程式專屬值):
使用在 Firebase 控制台中取得的供應商 ID,建立
OAuthProvider的執行個體。Swift
var provider = OAuthProvider(providerID: "oidc.example-provider")Objective-C
FIROAuthProvider *provider = [FIROAuthProvider providerWithProviderID:@"oidc.example-provider"];選用:指定要與 OAuth 要求一併傳送的其他自訂 OAuth 參數。
Swift
provider.customParameters = [ "login_hint": "user@example.com" ]Objective-C
[provider setCustomParameters:@{@"login_hint": @"user@example.com"}];請向供應商確認支援的參數。 請注意,您無法使用
setCustomParameters傳遞 Firebase 必要的參數。這些參數包括client_id、response_type、redirect_uri、state、scope和response_mode。選用:指定要向驗證服務供應商要求的其他 OAuth 2.0 範圍 (基本設定檔除外)。
Swift
provider.scopes = ["mail.read", "calendars.read"]Objective-C
[provider setScopes:@[@"mail.read", @"calendars.read"]];請向供應商確認支援的範圍。
選用:如要自訂應用程式向使用者顯示 reCAPTCHA 時,呈現
SFSafariViewController或UIWebView的方式,請建立符合AuthUIDelegate通訊協定的自訂類別。使用 OAuth 供應商物件向 Firebase 驗證。
Swift
// If you created a custom class that conforms to AuthUIDelegate, // pass it instead of nil: 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. // OAuth access token can also be retrieved: // (authResult.credential as? OAuthCredential)?.accessToken // OAuth ID token can also be retrieved: // (authResult.credential as? OAuthCredential)?.idToken } } }Objective-C
// If you created a custom class that conforms to AuthUIDelegate, // pass it instead of nil: [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. // OAuth access token can also be retrieved: // ((FIROAuthCredential *)authResult.credential).accessToken // OAuth ID token can also be retrieved: // ((FIROAuthCredential *)authResult.credential).idToken }]; } }];雖然上述範例著重於登入流程,但您也可以使用
linkWithCredential將 OIDC 供應商連結至現有使用者。舉例來說,您可以將多個供應商連結至同一位使用者,讓他們能使用任一供應商登入。Swift
Auth().currentUser.link(withCredential: credential) { authResult, error in if error != nil { // Handle error. } // OIDC credential is linked to the current user. // IdP data available in authResult.additionalUserInfo.profile. // OAuth access token can also be retrieved: // (authResult.credential as? OAuthCredential)?.accessToken // OAuth ID token can also be retrieved: // (authResult.credential as? OAuthCredential)?.idToken }Objective-C
[[FIRAuth auth].currentUser linkWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { if (error) { // Handle error. } // OIDC credential is linked to the current user. // IdP data available in authResult.additionalUserInfo.profile. // OAuth access token can also be retrieved: // ((FIROAuthCredential *)authResult.credential).accessToken // OAuth ID token can also be retrieved: // ((FIROAuthCredential *)authResult.credential).idToken }];reauthenticateWithCredential也可以使用相同的模式,用於擷取需要近期登入的機密作業的新憑證。Swift
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 can also be retrieved: // (authResult.credential as? OAuthCredential)?.accessToken // OAuth ID token can also be retrieved: // (authResult.credential as? OAuthCredential)?.idToken }Objective-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 can also be retrieved: // ((FIROAuthCredential *)authResult.credential).accessToken // OAuth ID token can also be retrieved: // ((FIROAuthCredential *)authResult.credential).idToken }];
手動處理登入流程
如果您已在應用程式中實作 OpenID Connect 登入流程,可以直接使用 ID 權杖向 Firebase 進行驗證:
Swift
let credential = OAuthProvider.credential(
withProviderID: "oidc.example-provider", // As registered in Firebase console.
idToken: idToken, // ID token from OpenID Connect flow.
rawNonce: nil
)
Auth.auth().signIn(with: credential) { authResult, error in
if error {
// Handle error.
return
}
// User is signed in.
// IdP data available in authResult?.additionalUserInfo?.profile
}
Objective-C
FIROAuthCredential *credential =
[FIROAuthProvider credentialWithProviderID:@"oidc.example-provider" // As registered in Firebase console.
IDToken:idToken // ID token from OpenID Connect flow.
rawNonce:nil];
[[FIRAuth auth] signInWithCredential:credential
completion:^(FIRAuthDataResult * _Nullable authResult,
NSError * _Nullable error) {
if (error != nil) {
// Handle error.
return;
}
// User is signed in.
// IdP data available in authResult.additionalUserInfo.profile
}];
後續步驟
使用者首次登入後,系統會建立新的使用者帳戶,並連結至使用者登入時使用的憑證,也就是使用者名稱和密碼、電話號碼或驗證提供者資訊。這個新帳戶會儲存為 Firebase 專案的一部分,可用於識別專案中所有應用程式的使用者,無論使用者如何登入。
在 Firebase Realtime Database 和 Cloud Storage安全性規則中,您可以從
auth變數取得已登入使用者的專屬使用者 ID,並用來控管使用者可存取的資料。
您可以將驗證供應商憑證連結至現有使用者帳戶,允許使用者透過多個驗證供應商登入應用程式。
如要將使用者登出,請呼叫 signOut:。
Swift
let firebaseAuth = Auth.auth() do { try firebaseAuth.signOut() } catch let signOutError as NSError { print("Error signing out: %@", signOutError) }
Objective-C
NSError *signOutError; BOOL status = [[FIRAuth auth] signOut:&signOutError]; if (!status) { NSLog(@"Error signing out: %@", signOutError); return; }
您也可以為所有驗證錯誤新增錯誤處理程式碼。請參閱「處理錯誤」。