在 Android 上使用 OpenID Connect 進行驗證

如果您已升級至 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 做為登入程序提供者:

  1. 將 Firebase 新增至 Android 專案。

  2. 如果尚未升級至 Firebase Authentication with Identity Platform,請先升級。只有升級後的專案才能使用 OpenID Connect 驗證。

  3. 在 Firebase 控制台中,依序前往「Security」(安全性) >「Authentication」(驗證)。

  4. 在「Sign-in method」(登入方式) 分頁中,依序點選「Add new provider」(新增供應商) 和「OpenID Connect」。

  5. 選取要使用授權碼流程或隱含授權流程。

    如果供應商支援授權碼流程,請一律使用該流程。隱含流程的安全性較低,強烈建議不要使用。

  6. 為這個供應商命名。記下系統產生的提供者 ID,例如 oidc.example-provider。在應用程式中加入登入程式碼時,您需要這個 ID。

  7. 指定用戶端 ID、用戶端密鑰和供應商的核發者字串。這些值必須與供應商指派給你的值完全一致。

  8. 儲存變更。

使用 Firebase SDK 處理登入流程

如果您正在建構 Android 應用程式,最簡單的方法是使用 Firebase Android SDK 處理整個登入流程,透過 OIDC 供應商使用 Firebase 驗證使用者。

如要使用 Firebase Android SDK 處理登入流程,請按照下列步驟操作:

  1. 使用 OAuthProvider 的 Builder 和供應商 ID 建構執行個體

    Kotlin

    val providerBuilder = OAuthProvider.newBuilder("oidc.example-provider")

    Java

    OAuthProvider.Builder providerBuilder = OAuthProvider.newBuilder("oidc.example-provider");

  2. 選用:指定要與 OAuth 要求一併傳送的其他自訂 OAuth 參數。

    Kotlin

    // Target specific email with login hint.
    providerBuilder.addCustomParameter("login_hint", "user@example.com")

    Java

    // Target specific email with login hint.
    providerBuilder.addCustomParameter("login_hint", "user@example.com");

    請向 OIDC 供應商確認支援的參數。請注意,您無法使用 setCustomParameters() 傳遞 Firebase 必要的參數。這些參數包括 client_id、response_type、redirect_uri、state、scope 和 response_mode。

  3. 選用:指定要向驗證服務供應商要求的其他 OAuth 2.0 範圍 (基本設定檔除外)。

    Kotlin

    // Request read access to a user's email addresses.
    // This must be preconfigured in the app's API permissions.
    providerBuilder.scopes = listOf("mail.read", "calendars.read")

    Java

    // Request read access to a user's email addresses.
    // This must be preconfigured in the app's API permissions.
    List<String> scopes =
            new ArrayList<String>() {
                {
                    add("mail.read");
                    add("calendars.read");
                }
            };
    providerBuilder.setScopes(scopes);

    請向 OIDC 供應商確認他們使用的範圍。

  4. 使用 OAuth 供應商物件向 Firebase 驗證。請注意,與其他 FirebaseAuth 作業不同,這項作業會彈出自訂 Chrome 分頁,接管 UI。因此,請勿在附加的 OnSuccessListener 和 OnFailureListener 中參照 Activity,因為作業啟動 UI 時,這些項目會立即卸離。

    請先確認是否已收到回覆。使用這個方法登入會將 Activity 移至背景,這表示系統可能會在登入流程中回收 Activity。為確保使用者在這種情況下不必重試,請檢查結果是否已存在。

    如要檢查是否有待處理的結果,請呼叫 getPendingAuthResult:

    Kotlin

    val pendingResultTask = firebaseAuth.pendingAuthResult
    if (pendingResultTask != null) {
        // There's something already here! Finish the sign-in for your user.
        pendingResultTask
            .addOnSuccessListener {
                // User is signed in.
                // IdP data available in
                // authResult.getAdditionalUserInfo().getProfile().
                // The OAuth access token can also be retrieved:
                // ((OAuthCredential)authResult.getCredential()).getAccessToken().
                // The OAuth secret can be retrieved by calling:
                // ((OAuthCredential)authResult.getCredential()).getSecret().
            }
            .addOnFailureListener {
                // Handle failure.
            }
    } else {
        // There's no pending result so you need to start the sign-in flow.
        // See below.
    }

    Java

    Task<AuthResult> pendingResultTask = firebaseAuth.getPendingAuthResult();
    if (pendingResultTask != null) {
        // There's something already here! Finish the sign-in for your user.
        pendingResultTask
                .addOnSuccessListener(
                        new OnSuccessListener<AuthResult>() {
                            @Override
                            public void onSuccess(AuthResult authResult) {
                                // User is signed in.
                                // IdP data available in
                                // authResult.getAdditionalUserInfo().getProfile().
                                // The OAuth access token can also be retrieved:
                                // ((OAuthCredential)authResult.getCredential()).getAccessToken().
                                // The OAuth secret can be retrieved by calling:
                                // ((OAuthCredential)authResult.getCredential()).getSecret().
                            }
                        })
                .addOnFailureListener(
                        new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                // Handle failure.
                            }
                        });
    } else {
        // There's no pending result so you need to start the sign-in flow.
        // See below.
    }

    如要啟動登入流程,請呼叫 startActivityForSignInWithProvider:

    Kotlin

    firebaseAuth
        .startActivityForSignInWithProvider(activity, provider.build())
        .addOnSuccessListener {
            // User is signed in.
            // IdP data available in
            // authResult.getAdditionalUserInfo().getProfile().
            // The OAuth access token can also be retrieved:
            // ((OAuthCredential)authResult.getCredential()).getAccessToken().
            // The OAuth secret can be retrieved by calling:
            // ((OAuthCredential)authResult.getCredential()).getSecret().
        }
        .addOnFailureListener {
            // Handle failure.
        }

    Java

    firebaseAuth
            .startActivityForSignInWithProvider(/* activity= */ this, provider.build())
            .addOnSuccessListener(
                    new OnSuccessListener<AuthResult>() {
                        @Override
                        public void onSuccess(AuthResult authResult) {
                            // User is signed in.
                            // IdP data available in
                            // authResult.getAdditionalUserInfo().getProfile().
                            // The OAuth access token can also be retrieved:
                            // ((OAuthCredential)authResult.getCredential()).getAccessToken().
                            // The OAuth secret can be retrieved by calling:
                            // ((OAuthCredential)authResult.getCredential()).getSecret().
                        }
                    })
            .addOnFailureListener(
                    new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            // Handle failure.
                        }
                    });

  5. 雖然上述範例著重於登入流程,但您也可以使用 startActivityForLinkWithProvider 將 OIDC 供應商連結至現有使用者。舉例來說,您可以將多個供應商連結至同一位使用者,讓他們能使用任一供應商登入。

    Kotlin

    // The user is already signed-in.
    val firebaseUser = firebaseAuth.currentUser!!
    firebaseUser
        .startActivityForLinkWithProvider(activity, provider.build())
        .addOnSuccessListener {
            // Provider credential is linked to the current user.
            // IdP data available in
            // authResult.getAdditionalUserInfo().getProfile().
            // The OAuth access token can also be retrieved:
            // authResult.getCredential().getAccessToken().
            // The OAuth secret can be retrieved by calling:
            // authResult.getCredential().getSecret().
        }
        .addOnFailureListener {
            // Handle failure.
        }

    Java

    // The user is already signed-in.
    FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
    
    firebaseUser
            .startActivityForLinkWithProvider(/* activity= */ this, provider.build())
            .addOnSuccessListener(
                    new OnSuccessListener<AuthResult>() {
                        @Override
                        public void onSuccess(AuthResult authResult) {
                            // Provider credential is linked to the current user.
                            // IdP data available in
                            // authResult.getAdditionalUserInfo().getProfile().
                            // The OAuth access token can also be retrieved:
                            // authResult.getCredential().getAccessToken().
                            // The OAuth secret can be retrieved by calling:
                            // authResult.getCredential().getSecret().
                        }
                    })
            .addOnFailureListener(
                    new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            // Handle failure.
                        }
                    });

  6. startActivityForReauthenticateWithProvider 也可以使用相同的模式,用於擷取需要近期登入的機密作業的新憑證。

    Kotlin

    // The user is already signed-in.
    val firebaseUser = firebaseAuth.currentUser!!
    firebaseUser
        .startActivityForReauthenticateWithProvider(activity, provider.build())
        .addOnSuccessListener {
            // User is re-authenticated with fresh tokens and
            // should be able to perform sensitive operations
            // like account deletion and email or password
            // update.
        }
        .addOnFailureListener {
            // Handle failure.
        }

    Java

    // The user is already signed-in.
    FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
    
    firebaseUser
            .startActivityForReauthenticateWithProvider(/* activity= */ this, provider.build())
            .addOnSuccessListener(
                    new OnSuccessListener<AuthResult>() {
                        @Override
                        public void onSuccess(AuthResult authResult) {
                            // User is re-authenticated with fresh tokens and
                            // should be able to perform sensitive operations
                            // like account deletion and email or password
                            // update.
                        }
                    })
            .addOnFailureListener(
                    new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            // Handle failure.
                        }
                    });

手動處理登入流程

如果您已在應用程式中實作 OpenID Connect 登入流程,可以直接使用 ID 權杖向 Firebase 進行驗證:

Kotlin

val providerId = "oidc.example-provider" // As registered in Firebase console.
val credential = oAuthCredential(providerId) {
    setIdToken(idToken) // ID token from OpenID Connect flow.
}
Firebase.auth
    .signInWithCredential(credential)
    .addOnSuccessListener { authResult ->
        // User is signed in.

        // IdP data available in:
        //    authResult.additionalUserInfo.profile
    }
    .addOnFailureListener { e ->
        // Handle failure.
    }

Java

AuthCredential credential = OAuthProvider
        .newCredentialBuilder("oidc.example-provider")  // As registered in Firebase console.
        .setIdToken(idToken)  // ID token from OpenID Connect flow.
        .build();
FirebaseAuth.getInstance()
        .signInWithCredential(credential)
        .addOnSuccessListener(new OnSuccessListener<AuthResult>() {
            @Override
            public void onSuccess(AuthResult authResult) {
                // User is signed in.

                // IdP data available in:
                //    authResult.getAdditionalUserInfo().getProfile()
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // Handle failure.
            }
        });

後續步驟

使用者首次登入後,系統會建立新的使用者帳戶,並連結至使用者登入時使用的憑證,也就是使用者名稱和密碼、電話號碼或驗證提供者資訊。這個新帳戶會儲存為 Firebase 專案的一部分,可用於識別專案中所有應用程式的使用者,無論使用者如何登入。

  • 在應用程式中,您可以從 FirebaseUser 物件取得使用者的基本個人資料。請參閱「管理使用者」。

  • 在 Firebase Realtime Database 和 Cloud Storage安全性規則中,您可以從 auth 變數取得已登入使用者的專屬使用者 ID,並用來控管使用者可存取的資料。

您可以將驗證供應商憑證連結至現有使用者帳戶,允許使用者透過多個驗證供應商登入應用程式。

如要登出使用者,請呼叫 signOut:

Kotlin

Firebase.auth.signOut()

Java

FirebaseAuth.getInstance().signOut();