# Use OhAuthCat SSO with Auth0

Use this guide when your application already signs users in with Auth0 and you want enterprise customers to sign in through their own identity provider with OhAuthCat, while Auth0 stays the user directory. After your callback obtains the verified OhAuthCat profile, the Auth0 helper finds or creates the matching Auth0 user.

## 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 Auth0

1. In Auth0, create a database connection that holds SSO users (for example `sso-users`). Users get a random password nobody knows, so they can sign in only through SSO.
2. Create a machine-to-machine application authorized for the Auth0 Management API with the scopes `read:users`, `create:users`, `update:users` and `delete:sessions`.
3. Store the domain, connection name, client ID and client secret as server-side configuration.

The helper creates the user with `user_id` set to the link key, so the Auth0 ID is `auth0|<key>` and lookups are exact rather than a search. It also writes the connection, organization and IdP subject under `app_metadata.ohauthcat`.

**Sessions.** The Management API cannot open an Auth0 login session. The supported pattern is to start your own application session for the Auth0 `user_id` the helper returns, exactly as you do after an Auth0 login today. Token-exchange features that may issue Auth0 tokens for an external identity depend on your Auth0 plan and are not wrapped by the helper.

## Node

```javascript
const auth0 = new Auth0Linker({
  domain: process.env.AUTH0_DOMAIN ?? "example.us.auth0.com",
  connection: "sso-users",
  clientId: process.env.AUTH0_CLIENT_ID ?? "placeholder",
  clientSecret: process.env.AUTH0_CLIENT_SECRET ?? "placeholder",
});

// Call with the verified profile from your SSO callback.
export async function linkUser(profile) {
  const { user, created } = await linkIdentity(profile, auth0, {
    onMissing: "create",
  });
  return { auth0UserId: user.userId, created };
}

export async function revokeUser(auth0UserId) {
  await auth0.revoke(auth0UserId);
}
```

## Python

```python
import os

from ohauthcat.existing_auth import Auth0Linker, LinkPolicy, link_identity

auth0 = Auth0Linker(
    domain=os.environ.get("AUTH0_DOMAIN", "example.us.auth0.com"),
    connection="sso-users",
    client_id=os.environ.get("AUTH0_CLIENT_ID", "placeholder"),
    client_secret=os.environ.get("AUTH0_CLIENT_SECRET", "placeholder"),
)


def link_user(profile):
    result = link_identity(profile, auth0, LinkPolicy("create"))
    return result.user.user_id, result.created


def revoke_user(auth0_user_id):
    auth0.revoke(auth0_user_id)
```

## Go

```go
package main

import (
	"context"
	"os"

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

func linkUser(ctx context.Context, profile ohauthcat.Profile) (string, error) {
	l, err := existingauth.NewAuth0Linker(existingauth.Auth0Options{
		Domain:       os.Getenv("AUTH0_DOMAIN"),
		Connection:   "sso-users",
		ClientID:     os.Getenv("AUTH0_CLIENT_ID"),
		ClientSecret: os.Getenv("AUTH0_CLIENT_SECRET"),
	})
	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 res.User.UserID, nil // start your application session for this user
}
```

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

Call `revoke` with the Auth0 user ID. It blocks the user and deletes their Auth0 sessions; a user that no longer exists is treated as already revoked. Also end your own application sessions for that user.

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.

- `provider_error` with status 403: the machine-to-machine application lacks a scope listed above.
- `email_conflict`: an Auth0 user with this email exists in the connection without the link. Link it explicitly or remove the duplicate.
- `invalid_input` on create: Auth0 database users need an email; profiles without one cannot be created.

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