# Use OhAuthCat SSO with Clerk

Use this guide when your application uses Clerk. After your callback obtains the verified OhAuthCat profile, the Clerk helper finds the user by `external_id`, creates one when your policy allows it, and issues a short-lived sign-in token that the browser redeems with the `ticket` strategy.

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

1. Use the instance's secret key (`sk_live_...` or `sk_test_...`) on the server only.
2. The helper sets `external_id` to the link key, creates users without a password, and stores the link under `private_metadata.ohauthcat`.
3. In the browser, call `signIn.create({ strategy: "ticket", ticket })` and then `setActive` with the created session. The token is valid for 300 seconds by default.

## Node

```javascript
const clerk = new ClerkLinker({
  secretKey: process.env.CLERK_SECRET_KEY ?? "sk_test_unset",
});

export async function linkUser(profile) {
  const { user } = await linkIdentity(profile, clerk, { onMissing: "create" });
  const { token } = await clerk.startSession(user);
  return token; // redeem in the browser with the ticket strategy
}

export async function revokeUser(clerkUserId) {
  await clerk.revoke(clerkUserId);
}
```

## Python

```python
import os

from ohauthcat.existing_auth import ClerkLinker, LinkPolicy, link_identity

clerk = ClerkLinker(secret_key=os.environ.get("CLERK_SECRET_KEY", "sk_test_unset"))


def link_user(profile):
    user = link_identity(profile, clerk, LinkPolicy("create")).user
    return clerk.start_session(user).token


def revoke_user(clerk_user_id):
    clerk.revoke(clerk_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.NewClerkLinker(existingauth.ClerkOptions{SecretKey: os.Getenv("CLERK_SECRET_KEY")})
	if err != nil {
		return "", err
	}
	res, err := existingauth.Link(ctx, existingauth.FromProfile(profile), l,
		existingauth.Policy{OnMissing: existingauth.OnMissingCreate})
	if err != nil {
		return "", err
	}
	token, err := l.StartSession(ctx, res.User, 0)
	return token.Token, err
}
```

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

Call `revoke` with the Clerk user ID. It bans the user, which ends all of their Clerk sessions and blocks new sign-ins.

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.

- `email_conflict` with `form_identifier_exists`: a Clerk user already uses this email without the link.
- `invalid_response` on find: more than one user carries the same `external_id`; remove the duplicate.
- `session_refused`: the user is banned.

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