# Use OhAuthCat SSO with Amazon Cognito

Use this guide when your application's users live in an Amazon Cognito user pool. After your callback obtains the verified OhAuthCat profile, the Cognito helper finds or creates the user with the admin APIs and starts a Cognito session through admin-initiated custom authentication, so your application keeps receiving Cognito tokens.

## 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 Amazon Cognito

1. The pool must accept plain usernames: the helper uses the link key as the username. Email can be an alias, but not the username attribute.
2. On the app client, enable `ALLOW_CUSTOM_AUTH` and add the Define, Create and Verify Auth Challenge Lambda triggers. The Verify trigger must accept a server-held answer that only your backend knows (keep it in a secret store, never in the browser).
3. Give the backend an IAM policy on the pool ARN with `cognito-idp:AdminGetUser`, `cognito-idp:AdminCreateUser`, `cognito-idp:AdminInitiateAuth`, `cognito-idp:AdminRespondToAuthChallenge`, `cognito-idp:AdminUserGlobalSignOut` and `cognito-idp:AdminDisableUser`.

Users are created with `MessageAction: SUPPRESS`, so Cognito sends no invitation. The SDK signs requests itself (AWS Signature Version 4) with static credentials. With rotating role credentials, pass your own transport that calls the AWS SDK instead.

## Node

```javascript
import {
  CognitoLinker,
  linkIdentity,
  sigV4CognitoTransport,
} from "@ohauthcat/node";

const cognito = new CognitoLinker({
  userPoolId: process.env.COGNITO_USER_POOL_ID ?? "ap-south-1_example",
  clientId: process.env.COGNITO_CLIENT_ID ?? "",
  transport: sigV4CognitoTransport({
    region: "ap-south-1",
    credentials: {
      accessKeyId: process.env.AWS_ACCESS_KEY_ID ?? "placeholder",
      secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY ?? "placeholder",
    },
  }),
});

export async function linkUser(profile) {
  const { user } = await linkIdentity(profile, cognito, {
    onMissing: "create",
  });
  return cognito.startSession(user, process.env.COGNITO_CHALLENGE_ANSWER ?? "");
}

export async function revokeUser(username) {
  await cognito.revoke(username);
}
```

## Python

```python
import os

from ohauthcat.existing_auth import (
    AwsCredentials,
    CognitoLinker,
    LinkPolicy,
    link_identity,
    sigv4_cognito_transport,
)

cognito = CognitoLinker(
    user_pool_id=os.environ.get("COGNITO_USER_POOL_ID", "ap-south-1_example"),
    client_id=os.environ.get("COGNITO_CLIENT_ID"),
    transport=sigv4_cognito_transport(
        region="ap-south-1",
        credentials=AwsCredentials(
            os.environ.get("AWS_ACCESS_KEY_ID", "placeholder"),
            os.environ.get("AWS_SECRET_ACCESS_KEY", "placeholder"),
        ),
    ),
)


def link_user(profile):
    user = link_identity(profile, cognito, LinkPolicy("create")).user
    return cognito.start_session(user, os.environ["COGNITO_CHALLENGE_ANSWER"])


def revoke_user(username):
    cognito.revoke(username)
```

## 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) (existingauth.CognitoSession, error) {
	transport, err := existingauth.SigV4Transport(existingauth.SigV4Options{
		Region: "ap-south-1",
		Credentials: existingauth.AWSCredentials{
			AccessKeyID:     os.Getenv("AWS_ACCESS_KEY_ID"),
			SecretAccessKey: os.Getenv("AWS_SECRET_ACCESS_KEY"),
		},
	})
	if err != nil {
		return existingauth.CognitoSession{}, err
	}
	l, err := existingauth.NewCognitoLinker(existingauth.CognitoOptions{
		UserPoolID: os.Getenv("COGNITO_USER_POOL_ID"),
		ClientID:   os.Getenv("COGNITO_CLIENT_ID"),
		Transport:  transport,
	})
	if err != nil {
		return existingauth.CognitoSession{}, err
	}
	res, err := existingauth.Link(ctx, existingauth.FromProfile(profile), l,
		existingauth.Policy{OnMissing: existingauth.OnMissingCreate})
	if err != nil {
		return existingauth.CognitoSession{}, err
	}
	return l.StartSession(ctx, res.User, os.Getenv("COGNITO_CHALLENGE_ANSWER"))
}
```

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

Call `revoke` with the Cognito username (the link key). It signs the user out of every device (`AdminUserGlobalSignOut`, which revokes refresh tokens) and disables the user. Access tokens already issued stay valid until they expire, so keep their lifetime short.

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.

- `session_refused` with provider code `NotAuthorizedException`: the Verify Auth Challenge trigger rejected the answer, or custom auth is not enabled on the app client.
- `email_conflict` with `AliasExistsException`: another user already holds this email as an alias.
- `provider_error` with `AccessDeniedException`: the IAM policy is missing an action above.
- If the app client has a secret, pass `clientSecret` so the helper sends `SECRET_HASH`.

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