Nonce Mismatch Issue with Firebase Authentication Using Keycloak ID Token

Hello everyone,

I’m in the process of integrating Firebase Authentication with Keycloak for my Angular application and have run into a problem regarding nonce validation between Keycloak and Firebase.

Context:

  1. Keycloak serves as my OpenID Connect (OIDC) provider, successfully returning an ID token after user login.
  2. Firebase is used for authentication following the retrieval of the ID token from Keycloak.
  3. My objective is to authenticate users with Firebase using the ID token obtained from Keycloak.

Here’s how I initialize Keycloak:

this.keycloak.init({
  config: this.appConstant.keycloakConfig,
  initOptions: {
    onLoad: 'check-sso',
    flow: 'standard',
    pkceMethod: 'S256',
    useNonce: true,  // Keycloak generates a nonce internally
  },
  enableBearerInterceptor: true,
});

After a successful Keycloak login, I retrieve the ID token and attempt to pass it to Firebase for sign-in:

async signInWithFirebase(idToken: string): Promise<any> {
  const auth = getAuth();
  const provider = new OAuthProvider(environment.firebaseConfig.oidcProvider);

  try {
    const credential = provider.credential({
      idToken,
      // rawNonce: '<rawNonce>', // Initially not passing rawNonce
    });

    const result = await signInWithCredential(auth, credential);
    return result;
  } catch (error: any) {
    console.error(error, 'Firebase sign-in error');
  }
}

Issues Encountered:

  1. When I do not pass the rawNonce: I receive the following error from Firebase:
FirebaseError: Nonce is missing in the request. (auth/missing-or-invalid-nonce)
  1. When I try passing the rawNonce that I decoded from the Keycloak ID token: I get this error instead:
FirebaseError: Firebase: The nonce in ID Token "<hashed_nonce>" does not match the SHA256 hash of the raw nonce "<rawNonce>" in the request. (auth/missing-or-invalid-nonce).

This indicates that while Firebase is now recognizing the presence of a nonce, there is a mismatch between the hashed nonce in the ID token and the rawNonce I provided.

Questions:

  1. Is there a way to access the raw nonce generated by Keycloak that matches the hashed value in the ID token?
  2. Can we configure Keycloak to accept a custom rawNonce that we generate and pass along to Firebase for validation?
  3. What is the recommended method for resolving the nonce mismatch issue when using Keycloak as an OIDC provider with Firebase?
  4. Would relying solely on PKCE (without utilizing a nonce) be a secure alternative in this scenario?

I have attempted to enable PKCE (pkceMethod: 'S256') in the Keycloak configuration, but Firebase still insists on requiring the nonce. Any assistance or guidance on this issue would be greatly appreciated!

Thank you in advance!