# Use OhAuthCat SSO with Firebase

Use this guide when your application signs users in with Firebase Authentication. After your callback obtains the verified OhAuthCat profile, the Firebase helper finds or creates the user (its `uid` is the link key) and mints a Firebase custom token that the browser exchanges with `signInWithCustomToken`.

## Identity-linking rule

The helper keys the user by the profile's `connection_id` and `idp_id`: the link key is `oac_` followed by the first 40 hex characters of SHA-256 over `connection_id`, a newline and `idp_id`. Email is never used to match. You choose the policy on every call: `refuse` signs in only users that are already linked, `create` also creates the missing user. When the provider already holds an unlinked account with the same email, the helper fails with `email_conflict`; link that account through a signed-in, explicit flow instead of merging on email.

## Set up Firebase

1. Create or reuse a service account for your Firebase project and load its `client_email` and `private_key` on the server. The helper signs custom tokens with that key (RS256, valid one hour); OhAuthCat never sees it.
2. Give the helper a small user store that wraps the Firebase Admin SDK you already use: `getUser(uid)` returning `null` when the user does not exist, and `createUser(input)`. Our SDK does not depend on the Firebase packages.
3. In the browser, call `signInWithCustomToken(auth, token)` with the token your backend returns.

## Node

```javascript
// Wrap firebase-admin's getAuth() here; this in-memory store keeps the example self-contained.
const users = new Map();
const firebase = () =>
  new FirebaseLinker({
    serviceAccount: {
      client_email: process.env.FIREBASE_CLIENT_EMAIL ?? "",
      private_key: process.env.FIREBASE_PRIVATE_KEY ?? "",
    },
    users: {
      getUser: async (uid) => users.get(uid) ?? null,
      createUser: async (input) => {
        users.set(input.uid, { uid: input.uid });
        return { uid: input.uid };
      },
    },
  });

export async function linkUser(profile) {
  const linker = firebase();
  const { user } = await linkIdentity(profile, linker, { onMissing: "create" });
  return linker.startSession(user, { org: profile.organization_id });
}

export async function revokeUser(uid) {
  // With firebase-admin: await auth.revokeRefreshTokens(uid); await auth.updateUser(uid, { disabled: true });
  users.delete(uid);
}
```

## Python

```python
import os

from ohauthcat.existing_auth import FirebaseLinker, FirebaseUser, LinkPolicy, link_identity


class Users:
    # Wrap firebase_admin.auth here; this in-memory store keeps the example self-contained.
    def __init__(self):
        self.users = {}

    def get_user(self, uid):
        return self.users.get(uid)

    def create_user(self, *, uid, email, email_verified, display_name):
        self.users[uid] = FirebaseUser(uid)
        return self.users[uid]


users = Users()


def firebase():
    return FirebaseLinker(
        client_email=os.environ["FIREBASE_CLIENT_EMAIL"],
        private_key=os.environ["FIREBASE_PRIVATE_KEY"],
        users=users,
    )


def link_user(profile):
    linker = firebase()
    user = link_identity(profile, linker, LinkPolicy("create")).user
    return linker.start_session(user, {"org": profile["organization_id"]})


def revoke_user(uid):
    # With firebase_admin: auth.revoke_refresh_tokens(uid); auth.update_user(uid, disabled=True)
    users.users.pop(uid, None)
```

## Go

```go
package main

import (
	"context"
	"os"

	ohauthcat "ohauthcat.com/sdk-go"
	"ohauthcat.com/sdk-go/existingauth"
)

// store wraps the Firebase Admin SDK's auth client and implements
// existingauth.FirebaseUserStore.
func linkUser(ctx context.Context, profile ohauthcat.Profile, store existingauth.FirebaseUserStore) (string, error) {
	l, err := existingauth.NewFirebaseLinker(existingauth.FirebaseOptions{
		ClientEmail:   os.Getenv("FIREBASE_CLIENT_EMAIL"),
		PrivateKeyPEM: os.Getenv("FIREBASE_PRIVATE_KEY"),
		Users:         store,
	})
	if err != nil {
		return "", err
	}
	res, err := existingauth.Link(ctx, existingauth.FromProfile(profile), l,
		existingauth.Policy{OnMissing: existingauth.OnMissingCreate})
	if err != nil {
		return "", err
	}
	return l.StartSession(res.User, map[string]any{"org": profile.OrganizationID})
}
```

## Revoke sessions on `dsync.user.deleted`

Firebase sessions are revoked through the Admin SDK you already use: revoke the user's refresh tokens and disable the user. ID tokens already issued stay valid for up to an hour unless your backend checks revocation when verifying them.

Verify the webhook first ([webhook verification](/events/webhook-verification/)), then map the directory user to your linked user through your own organization-scoped record. OhAuthCat does not close sessions in your provider for you.

## Troubleshooting

| Code                   | Meaning                                                                           |
| ---------------------- | --------------------------------------------------------------------------------- |
| `invalid_input`        | A profile field or option is missing or malformed                                 |
| `not_linked`           | No linked user and the policy is `refuse`                                         |
| `email_conflict`       | An unlinked account already uses this email or identifier                         |
| `provider_error`       | The provider refused the call (HTTP status in `status`)                           |
| `provider_unavailable` | Network failure, timeout, HTTP 429 or 5xx                                         |
| `invalid_response`     | The provider answered with an unexpected body                                     |
| `session_refused`      | The provider would not start a session (disabled, banned, wrong challenge answer) |

Error messages never contain tokens, secrets or provider response bodies, so they are safe to log.

- `invalid_input` when constructing the helper: the private key is not an RSA PEM key. Keep the newlines of the service account `private_key`.
- `invalid_input` on `startSession`: a custom claim uses a reserved name such as `sub` or `firebase`.
- `email_conflict`: your user store reported that the user ID or email already exists (`auth/email-already-exists`).
- Browser sign-in fails with an audience error: the service account belongs to a different Firebase project.

See also [working with existing auth](/sso/working-with-existing-auth/) and [profiles](/sso/profiles/).
