如果您已透過 Identity Platform 升級至 Firebase 驗證,則可以選擇符合 OpenID Connect (OIDC) 規定的供應商,透過 Firebase 驗證使用者。因此您可以使用 Firebase 未原生支援的識別資訊提供者。
事前準備
如要使用 OIDC 提供者登入使用者,您必須先向提供者收集一些資訊:
用戶端 ID:供應商專用的字串,用於識別應用程式。供應商可能會為您支援的每個平台指派不同的用戶端 ID。這是供應商核發的 ID 權杖中
aud
憑證附加資訊的其中一個值。用戶端密鑰:供應商用於確認用戶端 ID 擁有權的密鑰字串。每個用戶端 ID 都需要相符的用戶端密鑰。 (只有在使用驗證碼流程時,才需要提供這個值,我們強烈建議使用)。
核發者:可識別供應器的字串。這個值必須是網址,附加
/.well-known/openid-configuration
時是提供者 OIDC 探索文件的位置。舉例來說,如果核發者是https://auth.example.com
,則探索文件必須可在https://auth.example.com/.well-known/openid-configuration
存取。
取得上述資訊後,啟用 OpenID Connect 做為 Firebase 專案的登入提供者:
如果您尚未透過 Identity Platform 升級至 Firebase 驗證,請進行升級。只有已升級的專案才能使用 OpenID Connect 驗證。
在 Firebase 控制台的「Sign-in providers」 (登入供應商) 頁面上,依序點選「Add new provider」(新增供應商) 和「OpenID Connect」(OpenID Connect)。
選擇要使用授權碼流程還是隱含授權流程。
如果供應商支援程式碼流程,建議您一律使用程式碼流程。隱含流程的安全性較低,強烈建議不要使用。
為這個供應商命名。記下產生的提供者 ID,例如
oidc.example-provider
。在應用程式中新增登入程式碼時,會需要用到這個 ID。指定您的用戶端 ID 和用戶端密鑰,以及供應商的核發者字串。這些值必須與供應商指派給您的值完全相符。
儲存變更。
使用 Firebase SDK 處理登入流程
如要使用 OIDC 供應商透過 Firebase 驗證使用者,最簡單的方式就是使用 Firebase SDK 處理整個登入流程。
如要使用 Firebase Apple 平台 SDK 處理登入流程,請按照下列步驟操作:
在 Xcode 專案中新增自訂網址配置:
使用您在 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 即時資料庫和 Cloud Storage 安全性規則中,您可以透過
auth
變數取得登入使用者的專屬 ID,並使用該 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; }
您可能也想要針對各種驗證錯誤加入錯誤處理程式碼。請參閱處理錯誤。