Company sign-in (OIDC)
Sign in through your company's OpenID Connect identity provider, such as Keycloak, and end app sessions when the provider ends them.
Let employees sign in through your company's identity provider (IdP), such as
Keycloak. The IdP is the service that holds the company accounts and speaks
OpenID Connect (OIDC). The oidc option of createBetterConvexAuth adds one
IdP with the provider ID oidc.
A user who signs in through the IdP, or links it, then signs in only through the IdP. When the IdP ends the user's grant, the app sessions of that user end too.
Before you start
You need:
- a working auth setup. Complete Add authentication first;
- a confidential OIDC client at the IdP: a client with a client ID and a client secret;
SITE_URLin Convex and Nuxt, and the.convex.siteURL of your deployment (CONVEX_SITE_URL). The IdP calls the deployment there for central logout.
The browser reaches the IdP callback through the Nuxt auth proxy at
https://<site>/api/auth/callback/oidc. The IdP sends logout calls directly to
https://<deployment>.convex.site/api/auth/oidc/backchannel-logout.
Set up Keycloak
Change the realm settings first. Then import the client.
Realm settings
In Realm settings:
- On the Tokens tab, turn on Revoke Refresh Token.
- On the Tokens tab, set Access Token Lifespan to a value between 2 and 15 minutes. The default of 5 minutes is good.
- Make sure that each user has a verified email. For users from LDAP or from another identity provider, turn on Trust Email in that federation or identity provider.
Users without a verified email cannot sign in.
Server hostname
Set KC_HOSTNAME on the Keycloak server to its public URL, for example
https://sso.example.com. Then the issuer does not change with the request
host.
Client
Import this JSON as the client. Use Clients, Import client, or
kcadm.sh create clients -r <realm> -f client.json, or your Terraform
provider. Replace each <...> value first.
{
"clientId": "<client-id>",
"name": "<app name>",
"protocol": "openid-connect",
"enabled": true,
"publicClient": false,
"clientAuthenticatorType": "client-secret",
"secret": "<generated secret, or omit and copy it from the Credentials tab>",
"standardFlowEnabled": true,
"implicitFlowEnabled": false,
"directAccessGrantsEnabled": false,
"serviceAccountsEnabled": false,
"consentRequired": false,
"frontchannelLogout": false,
"redirectUris": ["https://<site>/api/auth/callback/oidc"],
"webOrigins": [],
"attributes": {
"pkce.code.challenge.method": "S256",
"post.logout.redirect.uris": "https://<site>/signed-out",
"backchannel.logout.url": "https://<deployment>.convex.site/api/auth/oidc/backchannel-logout",
"backchannel.logout.session.required": "true",
"backchannel.logout.revoke.offline.tokens": "false",
"use.refresh.tokens": "true",
"oauth2.device.authorization.grant.enabled": "false",
"oidc.ciba.grant.enabled": "false"
},
"defaultClientScopes": ["web-origins", "acr", "profile", "roles", "basic", "email"],
"optionalClientScopes": []
}What the settings do:
publicClient: falseandclientAuthenticatorType: the app proves itself with the client secret. Keep the secret out of the repository.standardFlowEnabled: the browser signs in with the authorization code flow. The app always sends PKCE S256, astate, and anonce.implicitFlowEnabled,directAccessGrantsEnabled,serviceAccountsEnabled, the device grant, and CIBA: keep them off. The app does not use them. Direct access grants would let a script send passwords to the IdP.consentRequired: keep it off. The app asks foropenid,email,profile, and the scopes inoidc.scopes.redirectUris: the callback of each site origin. Use exact URIs, no wildcards. Add one URI for each origin inSITE_URLandsiteOrigins.post.logout.redirect.uris: the pages that the IdP may return to after sign-out. Use exact URIs, no wildcards, one for each site origin. Separate several URIs with##.backchannel.logout.url: the route that ends app sessions when a user signs out at the IdP (central logout).frontchannelLogout: keep it off. The app supports back-channel logout only.use.refresh.tokens: keep it on. The app needs refresh tokens for the liveness check. Do not addoffline_accesstooidc.scopeson Keycloak: offline tokens outlive the SSO session, so the liveness check would no longer follow it.defaultClientScopes:emailandprofileput the email and the name into the ID token.
Audience for your own services
If the app calls your own services with the user's access token, each service
must find itself in the token's aud claim. For each service:
- In Client scopes, create a client scope.
- In that scope, add an Audience mapper. Set Included Client Audience to the client of the service.
- In the app client, on Client scopes, add the scope as Default.
Add the scope as Default, or as Optional and name it in oidc.scopes.
Configure the app
Store the IdP values in the Convex environment. Set them for each deployment:
pnpm exec better-convex-nuxt convex env set OIDC_ISSUER https://sso.example.com/realms/acme
pnpm exec better-convex-nuxt convex env set OIDC_CLIENT_ID acme-app
printf '%s' "$OIDC_CLIENT_SECRET" | pnpm exec better-convex-nuxt convex env set OIDC_CLIENT_SECRETDo not print or commit the client secret.
Pass oidc as a function. Convex calls it when it builds Better Auth, so a
missing variable fails that request and not the first deployment. Add it next
to the options you already have; the example shows only oidc:
import { createBetterConvexAuth } from '@lupinum/better-convex-nuxt/better-auth/server'
import { components } from './_generated/api'
import type { DataModel } from './_generated/dataModel'
function requireEnv(name: string): string {
const value = process.env[name]
if (!value) throw new Error(`${name} is required`)
return value
}
export const auth = createBetterConvexAuth<DataModel>(components.betterAuth, {
oidc: () => ({
issuer: requireEnv('OIDC_ISSUER'),
clientId: requireEnv('OIDC_CLIENT_ID'),
clientSecret: requireEnv('OIDC_CLIENT_SECRET'),
}),
})The oidc options:
| Option | Meaning |
|---|---|
issuer | The IdP's issuer URL. Required. |
clientId | The client ID. Required. |
clientSecret | The client secret. Required. |
scopes | More scopes besides openid email profile, for example offline_access on Entra ID and Okta. See Other identity providers. |
onSignIn | A function that runs at every IdP sign-in with the verified ID-token claims. See Roles and groups from the IdP. |
issuer must be an https URL. It must equal the issuer value of the IdP's
discovery document (<issuer>/.well-known/openid-configuration) exactly,
including a trailing slash. When the values differ, sign-in fails and the
Convex log shows AUTH_OIDC_ISSUER_MISMATCH with expected and received.
Warning: The issuer is part of the account key of every IdP user. If you
change the issuer, no IdP user can sign in to their old account again. They get
account_not_linked. Pin the issuer with KC_HOSTNAME before the first user
signs in.
The factory rejects oidc together with twoFactor, a socialProviders entry
named oidc, and oidc in account.accountLinking.trustedProviders. It throws
when the module loads, with a message that names the conflicting option. One
case is later: when socialProviders is a function that returns an oidc
entry, createAuth fails with AUTH_CONFIG_INVALID, and the Convex log shows
the message.
Nothing changes in nuxt.config.ts. The auth proxy already forwards
/api/auth/callback/*, and auth.registerRoutes(http) adds the logout route.
Sign in
Call client.signIn.social() with the provider oidc. Better Auth redirects the
browser to the IdP:
<script setup lang="ts">
definePageMeta({ convexAuth: 'guest' })
const route = useRoute()
const { client } = useConvexAuth()
const returnTo = useConvexAuthReturnTo()
const redirecting = ref(false)
const signInError = ref(
route.query.error === 'account_not_linked'
? 'This email already has an account. Sign in with your old method first, then link your company account in the settings. If you never had an account here, contact support.'
: route.query.error
? 'Sign in could not be completed.'
: '',
)
async function signInWithCompany() {
signInError.value = ''
redirecting.value = true
const result = await client.signIn.social({
provider: 'oidc',
callbackURL: returnTo.value ?? '/app',
errorCallbackURL: '/sign-in',
})
if (result.error) {
redirecting.value = false
signInError.value =
result.error.code === 'OIDC_UNAVAILABLE'
? 'Company sign-in is not available. Try again in a minute.'
: 'Sign in could not be completed.'
}
}
</script>
<template>
<button :disabled="redirecting" @click="signInWithCompany">
Sign in with your company account
</button>
<p v-if="signInError" role="alert">{{ signInError }}</p>
</template>When the IdP step fails, Better Auth sends the browser to errorCallbackURL
with an error query parameter:
| Where | Error | Meaning |
|---|---|---|
| Sign-in start | OIDC_UNAVAILABLE (503) | The IdP did not answer, or its discovery document is not valid. No redirect happens. Try again after 10 seconds. |
?error= | issuer_mismatch | The callback names another issuer. |
?error= | invalid_code | The IdP refused the authorization code, or the code was already used. |
?error= | unable_to_get_user_info | The ID token is not valid: signature, issuer, audience, expiry, or nonce. |
?error= | account_not_linked | A user with this email exists but has not linked the IdP. See Move existing password users. |
?error= | email_not_found | The ID token has no email. |
?error= | nonce_binding_missing | The sign-in was not started by this app for this provider. |
?error= | AUTH_USER_CREATE_UNVERIFIED_EMAIL | The IdP does not mark the email as verified. No user is created. |
?error= | OIDC_SIGN_IN_REFUSED | oidc.onSignIn threw. No session is created. The Convex log shows AUTH_OIDC_SIGN_IN_HOOK_REFUSED with the error. |
?error= | Any other value | The IdP refused the request, for example access_denied. The value comes from the IdP. |
| Callback response | 403 AUTH_USER_CREATE_REJECTED | beforeUserCreate refused the new user. Better Auth answers with an error response and does not redirect. |
Sign out of the app and the IdP
Pass disableRedirect: true to client.signOut(). Better Auth then returns
the IdP's sign-out URL, and your code navigates to it:
Warning: Always pass disableRedirect: true. Without it, Better Auth starts
its own navigation, and that navigation races your navigateTo() call.
const { client } = useConvexAuth()
const { data } = await client.signOut({ disableRedirect: true, callbackURL: '/signed-out' })
// The IdP ends its session, then returns to /signed-out.
if (data?.url) window.location.assign(data.url)
else await navigateTo('/')callbackURL is a public page in your app, such as /signed-out. Register
its full URL in post.logout.redirect.uris. The app session ends before the
browser leaves. A user without an IdP account gets no url. When the IdP does
not answer, the app signs out locally only and returns no url.
Central logout and liveness
Two mechanisms end app sessions when the IdP ends the user's grant.
Back-channel logout. The IdP calls the logout route when the user signs out at the IdP or an administrator ends the user's IdP sessions. The route ends every app session of that user, on every device, and deletes the stored IdP tokens. It works for all site origins. When the route cannot load the IdP keys, it answers 503. When it cannot end the sessions, it answers 500 and accepts the IdP's retry of the same logout token, up to three tries. If the IdP does not retry, the sessions end only when the liveness check later finds a refused refresh token. That does not happen with an IdP that keeps the refresh token after a sign-out, or with Google (see below). There the sessions stay until you revoke them with the Better Auth session API.
Liveness check. Before the app issues a Convex session token or an access
token for an MCP client, it checks the stored IdP access token. When that
token expires within 60 seconds, the app refreshes it at the IdP. If the IdP
refuses the refresh token, every app session of the user ends, and the MCP
client's token request fails with invalid_grant. Keycloak refuses it when:
- an administrator revoked the grant or disabled the user;
- the IdP session ended, also by idle or maximum time.
The app stores the IdP token's expiry at most 15 minutes ahead, so it asks the IdP at least every 15 minutes while the user is active, whatever lifetime the IdP gives its access tokens. With Keycloak's 5-minute default, almost every Convex token issue asks the IdP.
Microsoft Entra ID and Okta keep the refresh token after a sign-out at the IdP. There the check ends sessions only after a revocation or a disabled user, not after an IdP sign-out. Google issues no refresh token to this app, so there is no liveness check with Google.
How long a session can live after the IdP refused the grant:
- functions that use
auth.getUser(ctx)orauth.requireUser(ctx): the IdP access-token lifetime (counted as at most 15 minutes) plus 15 minutes, so about 20 minutes with Keycloak's 5-minute default and at most 30 minutes; - functions that use only
ctx.auth.getUserIdentity(): 15 minutes more (about 35 minutes with Keycloak's default); - an MCP client: until its next token request (MCP access tokens last 10
minutes). Tools that check
requireMcpPrincipalstop as soon as the sessions end; - without an open tab or MCP client: until the next visit.
An IdP that does not answer signs nobody out. But the app issues no new Convex
or MCP token for a grant it could not confirm for more than an hour after the
stored access token expired. It answers 503 OIDC_UNAVAILABLE until the IdP
answers again. The sessions stay, so nobody has to sign in again. The same
happens when the IdP rejects the client secret: rotate the secret in the IdP
and in Convex together.
When the stored IdP tokens cannot be read (for example after the auth secret changed without keeping the old one), the app cannot ask the IdP again, so the grant ends: the user's sessions end, and the user signs in again through the IdP.
One exception: if a refresh times out after the IdP already issued a new refresh token, the stored token is lost. The next refresh then signs the user out. The user signs in again through the IdP, usually without a password prompt.
A slow IdP can make one request fail. The refresh may take up to 10 seconds, but server rendering waits only 5 seconds for the Convex session token, and the browser 8 seconds. That page render or token request fails. The refresh still finishes and is stored, so the next request works and nobody is signed out.
With Keycloak, the app session follows the IdP session. Keycloak's SSO idle timeout (30 minutes by default) ends the app session after the tab was closed. An open tab keeps the IdP session alive up to Keycloak's SSO maximum. Without refresh tokens there is no liveness check, and only back-channel logout ends sessions.
Log codes
The Convex log shows these codes with [better-convex] AUTH_OIDC_FAILURE. Lines
about one user carry the Better Auth userId.
| Code | Meaning |
|---|---|
AUTH_OIDC_GRANT_ENDED | The IdP refused the refresh token. The user's sessions ended. |
AUTH_OIDC_LOGOUT_ENDED | A back-channel logout ended the user's sessions. |
AUTH_OIDC_GRANT_UNCHECKED | The IdP did not answer for more than an hour. New tokens are refused until it answers. |
AUTH_OIDC_CLIENT_REJECTED | The IdP rejected the client ID or secret. Check OIDC_CLIENT_SECRET. |
AUTH_OIDC_REFRESH_FAILED:<detail> | A refresh failed, for example network or timeout. After decrypt or subject, the grant ends. |
AUTH_OIDC_JWKS_FAILED | The IdP signing keys could not be loaded. |
AUTH_OIDC_KEY_UNKNOWN | A token named a signing key that the app has not loaded. The app loads the IdP keys again at most every 30 seconds, so a logout token signed with a new key within that time is refused. Then only the liveness check can end those sessions; see Central logout and liveness. Often a forged logout request. |
AUTH_OIDC_LOGOUT_REVOKE_FAILED | A back-channel logout could not end the sessions. The IdP may retry. |
AUTH_OIDC_SIGN_IN_HOOK_REFUSED | oidc.onSignIn threw, so the sign-in was refused. |
AUTH_OIDC_ISSUER_MISMATCH | The discovery document names another issuer. The line shows expected and received. |
Who may use the app
oidc.onSignIn runs at every sign-in through the IdP, after the user exists
and before the session is created. Throw to refuse the sign-in. The example
lets in only members of one Keycloak group.
The example reads the groups claim. Keycloak adds it only after you add the
group mapper; see Roles and groups from the IdP.
Without the mapper, the example refuses every user.
export const auth = createBetterConvexAuth<DataModel>(components.betterAuth, {
oidc: () => ({
issuer: requireEnv('OIDC_ISSUER'),
clientId: requireEnv('OIDC_CLIENT_ID'),
clientSecret: requireEnv('OIDC_CLIENT_SECRET'),
onSignIn: ({ claims }) => {
const groups = Array.isArray(claims.groups) ? claims.groups : []
if (!groups.includes('/acme-app/users')) throw new Error('Not a member of /acme-app/users')
},
}),
})A refused user gets no session. The user row stays, and the next sign-in runs
the check again. To limit new users only, use beforeUserCreate; see
Better Auth setup.
You can also gate the client in Keycloak, so the IdP refuses the sign-in before it reaches the app:
- In Authentication, duplicate the browser flow.
- In the copy, add a sub-flow with the requirement Conditional.
- In the sub-flow, add Condition - User Role. Select the app role and turn on Negate output.
- In the sub-flow, add Deny Access.
- In the app client, open Advanced, Authentication flow overrides, and set Browser Flow to the copy.
Both checks run at sign-in. Removing a group or role takes effect at the user's next IdP sign-in. To end the user's app sessions now, sign the user out in Keycloak: Users, the user, Sessions, Sign out. Keycloak then sends back-channel logout. If you disable the user in Keycloak, the app sessions end at the next refresh (see the liveness check above).
Roles and groups from the IdP
Copy roles or groups from the ID token into your own table in oidc.onSignIn.
Then your Convex functions check the table, in the same transaction as the
read or write they protect.
First put the groups into the ID token. In Keycloak:
- In Client scopes, create a client scope
groups. - Add a mapper Group Membership with Token Claim Name
groups. Turn on Full group path and Add to ID token. - In the app client, on Client scopes, add
groupsas Default.
Store the role per user:
import { defineSchema, defineTable } from 'convex/server'
import { v } from 'convex/values'
export default defineSchema({
members: defineTable({
userId: v.string(),
role: v.union(v.literal('admin'), v.literal('lead'), v.literal('member')),
}).index('by_userId', ['userId']),
})import { ConvexError, v } from 'convex/values'
import { internalMutation, query } from './_generated/server'
import { auth } from './auth'
// Called only from oidc.onSignIn. Internal, so no client can set a role.
// Returns false, and removes the role, when the user may not use the app.
export const syncGroups = internalMutation({
args: { userId: v.string(), groups: v.array(v.string()) },
handler: async (ctx, { userId, groups }) => {
const member = await ctx.db
.query('members')
.withIndex('by_userId', (q) => q.eq('userId', userId))
.unique()
if (!groups.includes('/acme-app/users')) {
if (member) await ctx.db.delete(member._id)
return false
}
const role = groups.includes('/acme-app/admins')
? 'admin'
: groups.includes('/acme-app/leads')
? 'lead'
: 'member'
if (member) await ctx.db.patch(member._id, { role })
else await ctx.db.insert('members', { userId, role })
return true
},
})
export const adminOverview = query({
args: {},
handler: async (ctx) => {
const user = await auth.requireUser(ctx)
const member = await ctx.db
.query('members')
.withIndex('by_userId', (q) => q.eq('userId', user.id))
.unique()
if (member?.role !== 'admin') throw new ConvexError({ code: 'FORBIDDEN' })
return { members: await ctx.db.query('members').take(100) }
},
})import { components, internal } from './_generated/api'
export const auth = createBetterConvexAuth<DataModel>(components.betterAuth, {
oidc: () => ({
issuer: requireEnv('OIDC_ISSUER'),
clientId: requireEnv('OIDC_CLIENT_ID'),
clientSecret: requireEnv('OIDC_CLIENT_SECRET'),
onSignIn: async ({ ctx, userId, claims }) => {
const groups = Array.isArray(claims.groups)
? claims.groups.filter((group): group is string => typeof group === 'string')
: []
const allowed = await ctx.runMutation(internal.members.syncGroups, { userId, groups })
if (!allowed) throw new Error('Not a member of /acme-app/users')
},
}),
})claims holds the verified ID-token claims, frozen. userId is the same as
user.id from auth.requireUser(ctx). ctx is the auth HTTP action's
context: use ctx.runMutation and ctx.runQuery. If the hook throws, also
from inside the mutation, the sign-in is refused, so a failing sync never
leaves a session with an old role. A refused user's role row is removed
first, so a session the user still has elsewhere loses the role too.
The roles change at each IdP sign-in. With Keycloak's default SSO timeouts a user signs in again at least every 10 hours. To apply a change now, sign the user out in Keycloak; back-channel logout ends the app sessions, and the next sign-in copies the new groups.
Linking the IdP to a signed-in user is not a sign-in and does not run the hook. Linking ends all of the user's sessions, including the current one, so the hook runs at the next sign-in.
Call your own services
auth.getOidcAccessToken(ctx) returns a current IdP access token for the
calling user. Use it in a Convex action to call your own services as that user:
import { ConvexError, v } from 'convex/values'
import { action } from './_generated/server'
import { auth } from './auth'
function requireEnv(name: string): string {
const value = process.env[name]
if (!value) throw new Error(`${name} is required`)
return value
}
export const summary = action({
args: { reportId: v.string() },
handler: async (ctx, { reportId }) => {
const { accessToken } = await auth.getOidcAccessToken(ctx)
const serviceUrl = new URL(
`/reports/${encodeURIComponent(reportId)}/summary`,
requireEnv('REPORTS_SERVICE_URL'),
)
const response = await fetch(serviceUrl, {
headers: { authorization: `Bearer ${accessToken}` },
})
if (!response.ok) throw new ConvexError({ code: 'REPORT_UNAVAILABLE' })
const body = (await response.json()) as { title?: unknown; total?: unknown }
if (typeof body.title !== 'string' || typeof body.total !== 'number') {
throw new ConvexError({ code: 'REPORT_UNAVAILABLE' })
}
return { title: body.title, total: body.total }
},
})The service checks the token's aud claim and decides what the user may read.
Warning: Never return the access token to the browser or to an MCP client, log it, or pass it to a scheduled function. Scheduled function arguments are stored. An MCP tool that needs your service calls it in the action and returns only the result.
The helper works only in actions. It throws ConvexError with data.code:
| Code | Meaning | What to do |
|---|---|---|
UNAUTHENTICATED | No valid session. | Send the user to sign-in. |
OIDC_ACCOUNT_REQUIRED | The user has no IdP account. | Ask the user to sign in through the IdP or link it. |
OIDC_SIGN_IN_REQUIRED | The IdP grant ended (the sessions have ended), or no refresh token is stored and the access token expired (the session is still there). | Start the IdP sign-in with client.signIn.social({ provider: 'oidc' }). Do not send the user to a guest-only sign-in page: it would send a signed-in user away. |
OIDC_UNAVAILABLE | The IdP did not answer in time, or the stored access token cannot be read. | Try again later. |
A call from a query or mutation throws TypeError with
AUTH_OIDC_ACCESS_TOKEN_REQUIRES_ACTION. Without the oidc option, it throws
TypeError with AUTH_OIDC_NOT_CONFIGURED.
The returned token has more than 60 seconds left. Otherwise the helper
refreshes it first. expiresAt is at most 15 minutes ahead, also when the IdP
token lives longer, because the app checks the grant at least that often. Only one refresh per user runs at a time, across all
actions and the Convex session token issue. The IdP access-token lifetime must be at least
2 minutes. A shorter lifetime makes the helper wait and then fail with
OIDC_UNAVAILABLE.
Cost of one call:
- one session read in the auth component and one account read;
- when the token needs a refresh: one rate-limit write, one more account read, one IdP token request, sometimes one IdP key request, and one account write, all within 10 seconds;
- while another call refreshes the same token: one account read every 500 ms, for at most 11 seconds.
It reads no application tables. When the IdP ended the grant, it deletes the user's sessions, which updates every query that reads them.
Move existing password users to the IdP
A password user with the same email cannot sign in through the IdP until they link it. Linking needs the same email at both sides, and the IdP must mark the email as verified.
The signed-in user links the IdP from a settings page:
const { client } = useConvexAuth()
await client.linkSocial({ provider: 'oidc', callbackURL: '/signed-out' })Linking ends all of the user's app sessions, including the current one. Send the user to a page that says "Your company account is linked. Sign in with it from now on." and offers the IdP sign-in.
After the link, the user is an IdP-managed user:
- password sign-in, email codes, and other social providers fail with
OIDC_SIGN_IN_REQUIRED(403); /change-passwordand/set-passwordfail withOIDC_SIGN_IN_REQUIREDbefore anything changes;- the app sends no password-reset email and no reset code;
/unlink-accountfails withOIDC_UNLINK_REFUSED(403);- linking a second IdP account fails with
OIDC_ACCOUNT_CONFLICT(403).
client.linkSocial() can also fail with Better Auth's link errors:
email_does_not_match (the IdP email differs from the user's email),
email_not_verified (the IdP does not mark the email as verified),
account_already_linked_to_different_user, and unable_to_link_account.
Move the users in this order:
- Turn on
oidc, and setemailAndPassword.disableSignUp: trueandemailOTP.disableSignUp: true. New sign-ups now come only through the IdP. An open sign-up would let anyone register an employee's address before the employee first signs in through the IdP. The employee would then getaccount_not_linked. - Ask users to link the IdP.
- When the last user has linked, turn off
emailAndPasswordandemailOTP.
If an employee gets account_not_linked but never had an account, somebody
registered the address before step 1. Delete that user (see
Account deletion), and the
employee can sign in through the IdP.
The library does not link users in bulk by email. That would trust an IdP email without proof from the user.
Local development
Choose one of two setups.
Local Convex deployment and local Keycloak.
- Create a local deployment with
pnpm exec better-convex-nuxt convex dev --anonymous. - Copy the Keycloak compose file from
test/fixtures/keycloakin the repository. SetKC_HOSTNAME=http://localhost:18080. - Set
OIDC_ISSUERtohttp://localhost:18080/realms/<realm>.httpis allowed only forlocalhost,127.0.0.1, and[::1]. - In the client JSON, use
http://localhost:3000/api/auth/callback/oidc,http://localhost:3000/signed-out, and the back-channel URLhttp://host.docker.internal:3211/api/auth/oidc/backchannel-logout.3211is the default HTTP actions port of a local deployment; checkCONVEX_SITE_URLin.env.local.
Cloud development deployment. A cloud deployment cannot reach localhost.
Use an issuer with a reachable https URL, for example a tunnel or a shared
development realm. Otherwise sign-in fails, and the Convex log shows
AUTH_OIDC_DISCOVERY_FAILED:network.
Other identity providers
The oidc option works with an IdP that provides:
- an OpenID Connect discovery document;
- ID tokens signed with an asymmetric key (RS, PS, ES, or EdDSA);
emailandemail_verified: truein the ID token (on Microsoft Entra ID,xms_edov: true);- client authentication with a client secret (
client_secret_basicorclient_secret_post); - refresh tokens, for the liveness check;
- back-channel logout (optional).
Only Keycloak is tested by this library. For the others, these are the settings that usually matter. Check them against your IdP's documentation:
| IdP | Settings |
|---|---|
| Microsoft Entra ID | Issuer https://login.microsoftonline.com/<tenant-id>/v2.0 (one tenant). scopes: ['offline_access'], plus api://<app-id>/<scope> for your own services. Add the optional ID-token claims email and xms_edov. Entra ID offers front-channel logout only, so only the liveness check applies. |
| Okta | The issuer of the authorization server you use, exactly (org or custom). scopes: ['offline_access'], and allow the refresh token grant for the app. |
| Google Workspace | Issuer https://accounts.google.com. No refresh token, so no liveness check, and getOidcAccessToken fails with OIDC_SIGN_IN_REQUIRED after about an hour. Check claims.hd in oidc.onSignIn to allow only your domain. |
| Auth0 | The issuer ends with /. Sign ID tokens with RS256. For your own services, set a default audience for the tenant. |
Not supported: Entra ID with several tenants (common or organizations),
because the issuer differs per tenant; client authentication with
private_key_jwt or mTLS; SAML; several IdPs at once.