# Signing in with Better Auth

> Connect the control plane to a Better Auth server as its identity provider, step by step, with groups for the roles and sign-out at Better Auth.

## What this guide sets up

Better Auth is a TypeScript library for authentication. With its OAuth provider plugin, a Better Auth server becomes an OpenID Connect identity provider. At the end of this guide, people sign in to the control plane with their Better Auth account, their groups give them their role in the control plane, and signing out of the control plane signs them out of Better Auth too. Password sign-in stays on for the local administrator, so you keep a way back in.

Unlike Keycloak, Better Auth has no admin console: the provider is code in your Better Auth server. This guide shows the code the control plane needs. The steps were tested in this order against Better Auth 1.7.7 with `@better-auth/oauth-provider` 1.7.7. **Single sign-on** explains every control plane setting in detail.

The examples use these values. Replace them with yours:

| Value | Example |
|---|---|
| The control plane's address, as people open it | `https://192.168.0.63:3443` |
| The Better Auth server's address (`baseURL`) | `https://192.168.0.63:9443` |
| Better Auth's path (`basePath`) | `/api/auth` |
| The groups | `onprem-ai-admins`, `onprem-ai-operators`, `onprem-ai-viewers` |

## Before you start

- **Both are reached over HTTPS.** Better Auth registers only `https://` redirect addresses for a web client, and refuses `localhost` and `127.0.0.1`: open the control plane at its network address. A plain IP address works; no DNS name is needed.
- **Better Auth trusts its own certificate.** At sign-out, Better Auth checks the sign-in answer the control plane sends back by fetching its own signing keys from its own address. When its certificate comes from your own certificate authority, start the Better Auth server with `NODE_EXTRA_CA_CERTS=/path/to/your-ca.pem`. Without it, sign-out ends at a Better Auth page that says "The id_token_hint is invalid".
- **You know the redirect URI.** Sign in to the control plane as an administrator, open **Configuration → Access → Sign-in**, and copy the **redirect URI**, for example `https://192.168.0.63:3443/api/auth/oidc/callback`. It is built from the address in your browser's address bar, so open the control plane at the address people will use.

## Step 1: The provider plugins in your Better Auth server

Add the `jwt` and `oauthProvider` plugins (`npm install @better-auth/oauth-provider`, the same version as `better-auth`), then run Better Auth's migration (`npx auth migrate`) for the tables they add.

```ts
import { betterAuth } from "better-auth";
import { jwt } from "better-auth/plugins";
import { oauthProvider } from "@better-auth/oauth-provider";

export const auth = betterAuth({
  baseURL: "https://192.168.0.63:9443",
  basePath: "/api/auth",
  emailAndPassword: { enabled: true },
  disabledPaths: ["/token"],
  plugins: [
    jwt(),
    oauthProvider({
      loginPage: "/sign-in",
      consentPage: "/consent",
      scopes: ["openid", "profile", "email", "groups"],
      advertisedMetadata: {
        scopes_supported: ["openid", "profile", "email", "groups"],
        claims_supported: ["preferred_username", "email", "groups"],
      },
      customIdTokenClaims: async ({ user }) => ({
        preferred_username: user.email,
        email: user.email,
        groups: await groupsOf(user), // your own lookup, see below
      }),
    }),
  ],
});
```

What each part is for:

- **`jwt()`** signs the sign-in answers (ID tokens) with a key pair, EdDSA by default, and publishes the public key. Without it, Better Auth signs with the client secret, publishes no signing keys, and **Test connection** says that the discovery document lacks `jwks_uri`.
- **`loginPage`** is your sign-in page. Better Auth sends people there with a signed query; your page must send that query back as `oauth_query` when it signs the person in. The `oauthProviderClient()` plugin of Better Auth's browser client does that for you.
- **`scopes` and `scopes_supported`** with `groups`: the control plane asks for the `groups` scope when the provider lists it, and Better Auth refuses every scope it does not know.
- **`customIdTokenClaims`** puts the person's groups and username into the ID token, where the control plane reads them. Better Auth has no groups of its own: `groupsOf` is your code, for example a lookup of the person's organization roles or of a table of yours. Better Auth also puts no `preferred_username` and no `email` into the ID token without this function, and a person who signs in for the first time without either is refused ("did not say who you are"). Return group names as plain strings, the same names you enter on the Configuration page.

The issuer URL is `baseURL` followed by `basePath`, here `https://192.168.0.63:9443/api/auth`, with no slash at the end. Check it: `https://192.168.0.63:9443/api/auth/.well-known/openid-configuration` must answer, with `groups` in `scopes_supported`.

## Step 2: The client for the control plane

Create one confidential client for the control plane. Better Auth manages clients only for a signed-in person, so run this with the session of an administrator of your Better Auth server, for example in a small script or an admin route of your own:

```ts
const client = await auth.api.adminCreateOAuthClient({
  headers, // the request headers of a signed-in administrator (their session cookie)
  body: {
    client_name: "onprem.ai control plane",
    redirect_uris: ["https://192.168.0.63:3443/api/auth/oidc/callback"],
    post_logout_redirect_uris: ["https://192.168.0.63:3443/signed-out"],
    token_endpoint_auth_method: "client_secret_basic",
    grant_types: ["authorization_code"],
    response_types: ["code"],
    scope: "openid profile email groups",
    skip_consent: true,
    enable_end_session: true,
    client_secret_expires_at: 0,
  },
});
// client.client_id and client.client_secret: the secret is shown this once.
```

- **`redirect_uris`**: the redirect URI from the Configuration page. When people open the control plane at more than one address, add the redirect URI of each one.
- **`post_logout_redirect_uris`** and **`enable_end_session: true`**: the control plane's address followed by `/signed-out`, one for each address. Without both, Logout ends only the control plane's session: the browser shows Better Auth's logout error, the Better Auth session stays, and the next sign-in needs no password.
- **`skip_consent: true`**: the control plane is your own application; without it, people see a consent page your Better Auth server must provide.
- Keep the client secret: you enter it in step 3. Better Auth stores only its hash.

## Step 3: Connect the control plane

Do this on the Configuration page, or from the deployment. The values are the same as for any identity provider; **Single sign-on** has both ways in detail.

### On the Configuration page

1. Open **Configuration → Access → Sign-in**.
2. Enter:
   - **Issuer URL**: `https://192.168.0.63:9443/api/auth`
   - **Client ID** and **Client secret**: from step 2.
   - **Name on the sign-in button**: for example `Company login`.
   - **Administrator group** `onprem-ai-admins`, **operator group** `onprem-ai-operators`, **viewer group** `onprem-ai-viewers`.
3. Click **Test connection**. A good result says that the discovery document and one signing key were fetched, that the issuer matches, and that the identity provider offers the `groups` scope.
4. Under **Login methods**, tick **Single sign-on**, keep **Password** ticked, and click **Save single sign-on settings**.

### From the deployment

On the control plane's machine, as root: write the client secret into `/var/lib/onprem-ai/control-plane/secrets/oidc_client_secret` (owner 1000, mode 0400, as **Single sign-on** shows), add these lines to `/etc/onprem-ai/control-plane/config.env`, and apply them with `sudo onprem-ai-ctl apply`:

```
LOGIN_METHODS=local,oidc
OIDC_ISSUER_URL=https://192.168.0.63:9443/api/auth
OIDC_CLIENT_ID=<client id from step 2>
OIDC_CLIENT_SECRET_FILE=/run/secrets/oidc_client_secret
OIDC_ADMINISTRATOR_GROUP=onprem-ai-admins
OIDC_OPERATOR_GROUP=onprem-ai-operators
OIDC_VIEWER_GROUP=onprem-ai-viewers
OIDC_DISPLAY_NAME=Company login
```

`sudo onprem-ai-ctl recovery show-sign-in` then shows `Login methods: local, oidc (from the deployment settings)` and `Client secret: set`.

When the Better Auth server's certificate comes from your own certificate authority, copy that authority's certificate into the folder `/etc/onprem-ai/trusted-certificate-authorities/` on the control plane's machine (**Trusting your own certificate authority**). Then run `sudo onprem-ai-ctl restart`.

## Step 4: Check that it works

Open the control plane's login page in a private browser window, at the address you registered in step 2.

1. Click **Sign in with Company login**, and sign in at your Better Auth sign-in page as a member of `onprem-ai-admins`. You come back to the control plane, signed in.
2. Open **Configuration → Access → Users**. The person is listed with the role **administrator**. Their username is their email address.
3. Sign in once as a member of each other group, and once as someone in none of the three: an operator, a viewer, and a viewer.
4. Click **Logout**. The browser goes to Better Auth and comes back to a page that says you are signed out. Click **Sign in with Company login** again: your Better Auth sign-in page asks for the password again.

## Optional: an Account link and single sign-on only

- When your Better Auth application has a page where people change their password or profile, enter it as the **account management URL** (`OIDC_ACCOUNT_URL`). Everyone signed in with single sign-on then finds **Account** in their user menu.
- **Single sign-on only** (`LOGIN_METHODS=oidc`) works as with every identity provider; sign in once as a member of the administrator group before you switch (see **Single sign-on**).

## When it does not work

| What you see | Why | What to do |
|---|---|---|
| **Test connection** says the discovery document lacks `jwks_uri` | The `jwt` plugin is missing | Add `jwt()` to the plugins (step 1) |
| **Test connection** says fetching the discovery document answered HTTP 404 | The issuer URL lacks Better Auth's path | Enter `baseURL` followed by `basePath`, for example `https://192.168.0.63:9443/api/auth` |
| **Test connection** says the identity provider states another issuer | The issuer URL ends with a `/`, or differs from Better Auth's `baseURL` | Enter the issuer exactly as the test names it |
| **Test connection** says the identity provider does not offer the `groups` scope, and warns about the groups | `groups` is not in `scopes_supported` | Add `groups` to `scopes` and `scopes_supported` (step 1). Groups from `customIdTokenClaims` still arrive, but list the scope so the control plane asks for it |
| Better Auth refuses to create the client: "web clients require https redirect URIs on non-loopback hosts" | A redirect address uses `http://`, `localhost` or `127.0.0.1` | Open the control plane at its HTTPS network address, and register that address |
| The person signs in at Better Auth but stays there, and never comes back to the control plane | Your sign-in page does not send the signed query back as `oauth_query` | Use Better Auth's `oauthProviderClient()` browser plugin, or send `oauth_query` yourself |
| The login page says that Better Auth refused the sign-in request; the audit log says `unauthorized_client` | The client ID or the client secret is wrong | Check the client ID; create a new secret (`rotateClientSecret`) and enter it |
| The login page says Better Auth did not say who you are | `customIdTokenClaims` is missing, or returns neither `preferred_username` nor `email` | Add it as in step 1 |
| Everyone is a viewer, also members of `onprem-ai-admins` | `customIdTokenClaims` returns no `groups`, or other names | Return the group names exactly as entered on the Configuration page |
| After **Logout**, Better Auth shows a logout error, and the next sign-in needs no password | The client has no `enable_end_session`, or no `post_logout_redirect_uris` with `/signed-out` | Set both on the client (step 2) |
| After **Logout**, Better Auth says "The id_token_hint is invalid" | Better Auth cannot fetch its own signing keys, usually because it does not trust its own certificate | Start it with `NODE_EXTRA_CA_CERTS` naming your certificate authority |
