The Vallenar del Río city council has a digital ID for its residents, and it wants it to work on AgendaViva too. It's the "Sign in with…" case you see on any website: another system checks who the person is and tells us. We don't see their password, we don't store it, and we inherit whatever second factor that system has.
In exchange, a third party joins the conversation, and almost everything that can go wrong lies in the round trips: someone stealing the code along the way, making another person finish a sign-in they started themselves, or taking over someone else's account because the email addresses match. In this lesson you'll see the standard protocol and what each piece protects, and you'll implement it with a library on top of the sessions we already have. Then, the criteria for when to stop doing it yourself.
- OAuth 2.0 and OpenID Connect
They're two standards, one on top of the other, and it's worth not confusing them:
- OAuth 2.0 solves delegated authorization: letting an application use an API on your behalf. Its result is an access token, which says what can be done, not who you are.
- OpenID Connect (OIDC) adds identity: an ID token signed by the provider that states "this person, with this identifier, has just signed in, for this application".
Signing in requires OIDC. Using an access token as proof of identity is a classic mistake: it may have been issued for another application. Some providers only offer OAuth 2.0 with a profile API; it can be done, but with rules specific to each one.
| Term | In our case |
|---|---|
| Provider (issuer) | The municipal ID |
| Client (relying party) | AgendaViva |
client_id and client_secret |
What the provider gives us when we register |
redirect_uri |
/api/sign-in/oidc/callback, registered in advance and compared character by character |
sub (subject) |
The person's stable identifier at that provider |
| Claims | The ID token data: sub, email, email_verified, name… |
1.1. The authorization code flow with PKCE
sequenceDiagram
participant N as Browser
participant A as AgendaViva
participant P as Provider
N->>A: GET /api/sign-in/oidc
A->>A: generates state, nonce and verifier
A-->>N: attempt cookie and redirect
N->>P: authorization: client_id, redirect_uri, state, nonce, challenge
P->>N: the person signs in and consents
P-->>N: redirect with code and state
N->>A: GET /callback?code=…&state=… and the cookie
A->>A: is the state this browser's?
A->>P: code, verifier and client_secret (server to server)
P-->>A: signed ID token
A->>A: signature, issuer, audience, expiry, nonce
A-->>N: AgendaViva session
| Piece | Attack it stops |
|---|---|
| Code instead of token | The token never passes through the browser, its history or the logs |
| PKCE: the hash of a secret verifier is sent, and the verifier is shown when redeeming | Whoever steals the code can't redeem it |
state, tied to the browser with a cookie |
An attacker making a sign-in of theirs finish in your browser, so you end up using their account without knowing |
nonce, inside the ID token |
An ID token from another attempt being reused |
Exact redirect_uri |
The code being sent somewhere else |
| Validating the ID token | Getting us to accept one issued by someone else, for someone else, or expired |
PKCE and the nonce partly cover the same ground as state. All three are used: they cost nothing, and not all providers are equally rigorous.
- Choosing the tool
None of this is written by hand. Validating the ID token on its own (downloading and rotating keys, allowed algorithms, issuer, audience) is already a well-known source of vulnerabilities. Here's where the options stand at the end of 2026:
| Option | What it is | Status |
|---|---|---|
openid-client 6 |
OAuth 2 and OIDC client, certified by the OpenID Foundation, for Node ≥ 20 | Maintained, with frequent releases |
| Better Auth | A complete system: accounts, sessions, providers, second factor, passkeys, organizations | Active. It joined Vercel in July 2026 |
| Auth.js (NextAuth) | Sessions and many providers | Maintained by the Better Auth team. Version 4 is the stable one and 5 is still in beta; for new projects, its maintainers recommend Better Auth |
arctic |
Lightweight OAuth clients for many providers | Marked on npm as unsupported since its last release, from 2025 |
lucia |
Session library | Deprecated; it remains as learning material |
| Managed services | Accounts, sessions and screens on someone else's infrastructure | Several. The Next.js documentation lists them |
Our need is specific: a provider that speaks OIDC, on top of our own accounts and sessions, which already exist. openid-client does exactly the protocol part and has no opinion on the rest. Better Auth would bring its own tables and sessions, and would replace 08-01 and 08-02: it's an excellent option for starting out, and a house move when you already have a home. Section 7 comes back to the decision.
Versions and maintainers change. Before choosing, check for yourself the date of the latest release, the security advisories and who's behind it.
npm install openid-client@6
# A test provider, for development only
docker run --rm -p 8080:8080 ghcr.io/navikt/mock-oauth2-server:7# .env.local (the same keys, with no value, in .env.example)
OIDC_ISSUER=http://localhost:8080/default
OIDC_CLIENT_ID=agendaviva
OIDC_CLIENT_SECRET=dev-secretmock-oauth2-server accepts any client and shows a form where you type the username and, in JSON, whatever claims you want. It's perfect for testing the odd cases and, obviously, good for nothing else.
- The configuration
// lib/env.ts: OIDC_ISSUER, OIDC_CLIENT_ID and OIDC_CLIENT_SECRET, optional. In the transformation:
oidc:
variables.OIDC_ISSUER && variables.OIDC_CLIENT_ID && variables.OIDC_CLIENT_SECRET
? {
issuer: variables.OIDC_ISSUER,
clientId: variables.OIDC_CLIENT_ID,
clientSecret: variables.OIDC_CLIENT_SECRET,
}
: null,// lib/db/schema.ts (added; imports primaryKey)
export const externalAccounts = pgTable(
'external_accounts',
{
provider: text('provider').notNull(),
subject: text('subject').notNull(),
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
primaryKey({ columns: [table.provider, table.subject] }),
index('external_accounts_user_idx').on(table.userId),
],
)The key is (provider, sub), not the email. Email addresses change, get reassigned and, with some providers, are typed in by the person themselves; sub is stable and unique within the issuer. A person can have several rows, one per provider. We don't store the tokens: we only want to know who it is, and a stored access token is one more secret to protect. Generate and apply the external-accounts migration.
- The round trip
// lib/oidc.ts
import 'server-only'
import { cookies } from 'next/headers'
import * as oidc from 'openid-client'
import * as z from 'zod'
import { readEnv } from '@/lib/env'
import { SITE_URL } from '@/lib/site'
const CALLBACK_PATH = '/api/sign-in/oidc/callback'
const IN_PRODUCTION = process.env.NODE_ENV === 'production'
const ATTEMPT_COOKIE = IN_PRODUCTION ? '__Host-agendaviva-oidc' : 'agendaviva-oidc'
const COOKIE_OPTIONS = {
httpOnly: true,
secure: IN_PRODUCTION,
sameSite: 'lax',
path: '/',
} as const
let config: Promise<oidc.Configuration> | null = null
async function discover(): Promise<oidc.Configuration> {
const { oidc: settings } = readEnv()
if (!settings) throw new Error('External provider not configured')
const issuer = new URL(settings.issuer)
const isLocal = issuer.protocol === 'http:' && issuer.hostname === 'localhost'
return oidc.discovery(issuer, settings.clientId, settings.clientSecret, undefined, {
timeout: 5, // Seconds, also for later requests
execute: isLocal ? [oidc.allowInsecureRequests] : [],
})
}
function getConfig(): Promise<oidc.Configuration> {
config ??= discover().catch((error: unknown) => {
config = null // It's tried again next time
throw error
})
return config
}
const attemptSchema = z.object({
verifier: z.string(),
state: z.string(),
nonce: z.string(),
returnTo: z.string(),
linkTo: z.string().nullable(),
})
export type SignInAttempt = z.output<typeof attemptSchema>
// Only from Server Actions and Route Handlers. Returns the provider's URL
export async function startSignIn(
options: Pick<SignInAttempt, 'returnTo' | 'linkTo'>,
): Promise<string> {
const provider = await getConfig()
const attempt: SignInAttempt = {
...options,
verifier: oidc.randomPKCECodeVerifier(),
state: oidc.randomState(),
nonce: oidc.randomNonce(),
}
const cookieStore = await cookies()
cookieStore.set(ATTEMPT_COOKIE, JSON.stringify(attempt), { ...COOKIE_OPTIONS, maxAge: 10 * 60 })
return oidc.buildAuthorizationUrl(provider, {
redirect_uri: new URL(CALLBACK_PATH, SITE_URL).href,
scope: 'openid email profile',
code_challenge: await oidc.calculatePKCECodeChallenge(attempt.verifier),
code_challenge_method: 'S256',
state: attempt.state,
nonce: attempt.nonce,
}).href
}
// Each attempt can be collected once
async function takeAttempt(): Promise<SignInAttempt | null> {
const cookieStore = await cookies()
const text = cookieStore.get(ATTEMPT_COOKIE)?.value
cookieStore.set(ATTEMPT_COOKIE, '', { ...COOKIE_OPTIONS, maxAge: 0 })
try {
return text ? attemptSchema.parse(JSON.parse(text)) : null
} catch {
return null
}
}
const claimsSchema = z.object({
sub: z.string().min(1).max(255),
email: z.email().max(254).toLowerCase().optional().catch(undefined),
email_verified: z.boolean().optional().catch(undefined),
name: z.string().trim().min(1).max(80).optional().catch(undefined),
})
export interface ExternalIdentity {
subject: string
email: string | null // Only if the provider vouches for it
name: string
}
export async function finishSignIn(
search: string,
): Promise<{ attempt: SignInAttempt; identity: ExternalIdentity } | null> {
const attempt = await takeAttempt()
if (!attempt) return null
try {
const callbackUrl = new URL(CALLBACK_PATH + search, SITE_URL)
const tokens = await oidc.authorizationCodeGrant(await getConfig(), callbackUrl, {
pkceCodeVerifier: attempt.verifier,
expectedState: attempt.state,
expectedNonce: attempt.nonce,
idTokenExpected: true,
})
const claims = claimsSchema.parse(tokens.claims())
const email = claims.email_verified === true ? (claims.email ?? null) : null
return {
attempt,
identity: { subject: claims.sub, email, name: claims.name ?? 'No name' },
}
} catch (error) {
console.error('External sign-in failed:', error instanceof Error ? error.name : error)
return null
}
}discoveryasks the issuer for its configuration (URLs and public keys) and checks that it claims to be who it is. The result is kept in a module variable. That doesn't contradict 03-04: there's nothing from any visitor in it, and the promise is stored so that a hundred simultaneous sign-ins make a single request.allowInsecureRequestsonly withhttp://localhost. In every other case, HTTP is rejected.- The attempt lives in a ten-minute
HttpOnlycookie. That's what ties the callback to this browser. There's no need to encrypt it: whoever edits it only spoils their own attempt, andreturnTowill be checked again. Laxis essential: the callback is a navigation coming from the provider. If one responds with aPOST(response_mode=form_post), this cookie wouldn't arrive and it would have to be rethought.- The callback URL is rebuilt with
SITE_URL, not withrequest.url: behind a proxy, the server thinks it's calledlocalhost, and the provider compares theredirect_uricharacter by character. authorizationCodeGrantvalidates everything:state, the PKCE redemption, and the ID token's signature, issuer, audience, expiry andnonce. If anything doesn't add up, it throws.email_verifiedis required to betrue. Missing isn't true.- The error's name is logged, not the error: its content may include the provider's response.
- Recognize, create or link
We know it's person sub at that provider. Which AgendaViva account does it correspond to?
flowchart TD
I["Verified identity"] --> V{"Linking requested<br/>from a session?"}
V -- "yes, and it's the same person" --> L["Link to that account"]
V -- no --> C{"(provider, sub) known?"}
C -- yes --> S["Session for that account"]
C -- no --> M{"Verified email?"}
M -- no --> R1["Not created: ask for another method"]
M -- yes --> E{"Is there already an account with that email?"}
E -- no --> N["Create account and link"]
E -- yes --> R2["Not merged automatically:<br/>sign in and link"]
The last branch is the delicate decision. Merging automatically by email is convenient and turns every provider into a master key for every account: it only takes one that doesn't verify email addresses properly, or that reassigns them (the address of an employee who left, for example), to get into someone else's account. OWASP and NIST ask for the same thing: to add an identity to an account, you have to be inside that account. Someone who already has a password signs in with it and links from "My account".
// lib/data/external-accounts.ts
import 'server-only'
import { and, eq } from 'drizzle-orm'
import { getDb } from '@/lib/db/client'
import { externalAccounts, users } from '@/lib/db/schema'
import type { ExternalIdentity } from '@/lib/oidc'
const PROVIDER = 'municipal'
export type ExternalResult =
| { status: 'ready'; userId: string }
| { status: 'no-email' | 'email-taken' }
export async function signInWithIdentity(
identity: ExternalIdentity,
): Promise<ExternalResult> {
const db = await getDb()
return db.transaction(async (tx): Promise<ExternalResult> => {
const [known] = await tx
.select({ userId: externalAccounts.userId })
.from(externalAccounts)
.where(
and(
eq(externalAccounts.provider, PROVIDER),
eq(externalAccounts.subject, identity.subject),
),
)
.limit(1)
if (known) return { status: 'ready', userId: known.userId }
if (!identity.email) return { status: 'no-email' }
const [created] = await tx
.insert(users)
.values({ name: identity.name, email: identity.email })
.onConflictDoNothing({ target: users.email })
.returning({ id: users.id })
if (!created) return { status: 'email-taken' }
await tx
.insert(externalAccounts)
.values({ provider: PROVIDER, subject: identity.subject, userId: created.id })
return { status: 'ready', userId: created.id }
})
}
export async function linkIdentity(userId: string, subject: string): Promise<boolean> {
const db = await getDb()
const rows = await db
.insert(externalAccounts)
.values({ provider: PROVIDER, subject, userId })
.onConflictDoNothing()
.returning({ subject: externalAccounts.subject })
return rows.length > 0 // false: it was already linked, perhaps to another account
}An account created this way has no password: passwordHash is null, and verifyPassword(…, null) always returns false. The person can set one with the recovery flow, because their email is verified. The role, as in 08-02, is the default one.
- The routes
// app/api/sign-in/oidc/route.ts
import type { NextRequest } from 'next/server'
import { redirect } from 'next/navigation'
import { safeDestination } from '@/lib/destination'
import { startSignIn } from '@/lib/oidc'
export async function GET(request: NextRequest) {
const returnTo = safeDestination(request.nextUrl.searchParams.get('returnTo'))
let destination: string
try {
destination = await startSignIn({ returnTo, linkTo: null })
} catch (error) {
console.error('Could not start an external sign-in:', error)
destination = '/sign-in?notice=external'
}
redirect(destination)
}// app/api/sign-in/oidc/callback/route.ts
import type { NextRequest } from 'next/server'
import { redirect } from 'next/navigation'
import { linkIdentity, signInWithIdentity } from '@/lib/data/external-accounts'
import { safeDestination } from '@/lib/destination'
import { finishSignIn } from '@/lib/oidc'
import { createSession, getCurrentUser } from '@/lib/session'
import { audit } from '@/lib/tasks/audit'
export async function GET(request: NextRequest) {
const result = await finishSignIn(request.nextUrl.search)
if (!result) redirect('/sign-in?notice=external')
const { attempt, identity } = result
if (attempt.linkTo) {
const user = await getCurrentUser()
if (!user || user.id !== attempt.linkTo) redirect('/sign-in?notice=external')
const linked = await linkIdentity(user.id, identity.subject)
if (linked) audit(user.id, 'account.linked', user.id)
redirect(linked ? '/account' : '/account?notice=already-linked')
}
const account = await signInWithIdentity(identity)
if (account.status !== 'ready') redirect(`/sign-in?notice=${account.status}`)
await createSession(account.userId)
audit(account.userId, 'session.started', account.userId)
redirect(safeDestination(attempt.returnTo))
}- A
GETthat writes, and it's the well-known exception: the protocol comes back with a navigation. What makes it safe is thestateand the fact that the code works only once. Repeating the callback, for example by reloading, finds the cookie deleted and ends up at/sign-in. redirectis outside thetry, as always. In a Route Handler it responds with a 307.- The session is ours. From here on, nothing distinguishes someone who signed in with a password. Signing out of AgendaViva doesn't sign you out of the provider; if that's needed, OIDC defines a coordinated logout.
6.1. The button and the account page
// SignInForm, below the form
<a href={`/api/sign-in/oidc?returnTo=${encodeURIComponent(returnTo)}`} className="mt-4 underline">
Sign in with your municipal ID
</a>
// SignInContent: the notice is chosen by key, the text from the URL is never rendered
const NOTICES = {
external: "We couldn't complete the sign-in. Please try again.",
'no-email': "The provider doesn't confirm your email address. Sign up with a password.",
'email-taken': 'You already have an account with that email address. Sign in with your password and link it in "My account".',
}
const { returnTo: requested, notice } = await searchParams
const text =
typeof notice === 'string' && Object.hasOwn(NOTICES, notice)
? NOTICES[notice as keyof typeof NOTICES]
: nullIt's an <a> and not a <Link>: it goes to another domain, and prefetching it would create attempts nobody asked for. "Email taken" does reveal that the account exists, but only to someone who has proved to the provider that they own that email address.
// actions/account.ts (added)
export async function linkAccount(): Promise<void> {
const user = await requireUser('/account')
redirect(await startSignIn({ returnTo: '/account', linkTo: user.id }))
}
export async function signOutOtherSessions(): Promise<void> {
const user = await requireUser('/account')
await endOtherSessions(user.id)
}// app/(public)/account/page.tsx
import { Suspense } from 'react'
import { linkAccount, signOutOtherSessions } from '@/actions/account'
import { SubmitButton } from '@/components/submit-button'
import { requireUser } from '@/lib/session'
export default function AccountPage() {
return (
<>
<h1 className="mb-6 text-3xl font-bold">My account</h1>
<Suspense fallback={<div aria-hidden className="h-32" />}>
<AccountDetails />
</Suspense>
</>
)
}
async function AccountDetails() {
const user = await requireUser('/account')
return (
<>
<p className="mb-4">{user.name}</p>
<form action={linkAccount}>
<SubmitButton pendingText="One moment…">Link your municipal ID</SubmitButton>
</form>
<form action={signOutOtherSessions}>
<SubmitButton pendingText="Signing out…">Sign out of other sessions</SubmitButton>
</form>
</>
)
}Linking starts in a Server Action, not in the GET. It's a sensitive change to the account: if a URL were enough, another website could trigger it in your browser, and if it had previously managed to get you signed in to its session at the provider, its identity would end up linked to your account. The action's POST can't be triggered from outside (08-06), and the callback also checks that the same session is still there. In a more sensitive system you'd ask for the password again, and send an email notification for every identity added.
Add account.linked to AuditedAction, a notice for already-linked and a link to /account in AccountMenu.
{ "email": "[email protected]", "email_verified": true, "name": "Test Resident" }Click "Sign in with your municipal ID", type any username (it will be the sub) and paste that JSON into the claims. Repeat with "email_verified": false, with [email protected], and with the same username and a different email: the last one must get into the earlier account, because sub is what counts. Then copy the callback URL and open it in a private window: without the attempt cookie, you don't get in.
- When to stop doing it by hand
What we've built over three lessons is small and can be understood in full. These are the signs that you need something more:
| Need | Our approach | Full library | Managed service |
|---|---|---|---|
| Password and one provider | Yes | Yes | Yes |
| Five providers with their quirks | Ongoing work | Yes | Yes |
| Second factor and recovery codes | A lot of delicate work | Yes | Yes |
| Passkeys | With a dedicated library | Yes | Yes |
| Organizations, invitations, permissions | By hand | Yes | Yes |
| SAML for enterprise customers | No | Depends on which | Yes |
| People's data in your database | Yes | Yes | No, or synced |
| Cost and dependency | Your time | Updates | Fees and vendor |
The honest criterion: if authentication isn't your product and you're starting today, a full library like Better Auth saves you almost this entire module except 08-04, which is always yours. A managed service adds screens, abuse detection and someone to call, in exchange for identities living elsewhere: check with compliance where they're hosted and what data processing agreement is needed. What you've learned is useful in all three cases, because you need to understand what the piece you choose does. And whichever it is, an outdated authentication library is worse than none: subscribe to its security advisories.
7.1. Passkeys
A passkey (WebAuthn) replaces the password with a key pair: the private key never leaves the device or the password manager, and the public key is all the server stores. There's nothing to steal in the database, and it resists phishing, because the browser binds it to the domain: on a lookalike site, it simply doesn't work. To implement them there's @simplewebauthn/server (version 14 requires Node 22), and the full libraries include them. If you were designing sign-in from scratch today, they should be on the list, along with the usual question: how is the account recovered when the device is lost? That recovery path sets the real security of the whole.
Common Mistakes and Tips
- Writing the protocol by hand, or decoding the ID token without validating it.
- Using an access token as proof of identity.
- Recognizing the person by email instead of by
(issuer, sub). - Merging accounts automatically because the email matches.
- Assuming
email_verifiedis true when it's missing. - Omitting
state, or storing it in a server variable, where it isn't tied to any browser. - Reusing the verifier, the
stateor thenonce. - Building the
redirect_urifrom theHostheader. - An attempt cookie with
SameSite=Strict: it doesn't arrive on the callback. - Linking to the start with
<Link>. - Storing provider tokens without needing them.
- Rendering the
error_descriptionthat arrives in the URL. - The client secret in a
NEXT_PUBLIC_variable.
Exercises
Exercise 1: what breaks if it's missing
For each omission, describe a specific attack: (a) state isn't checked; (b) PKCE isn't used and the code shows up in a proxy's logs; (c) the ID token's audience (aud) isn't checked; (d) accounts are merged by email without looking at email_verified; (e) returnTo isn't checked at the end.
Solution
- (a) The attacker starts signing in with their identity, keeps the callback URL without opening it and gets the victim to open it. The victim ends up inside the attacker's account without noticing, and whatever they write there, the attacker will see.
- (b) Whoever reads those logs redeems the code before we do, if they also get hold of the secret or the client is public. With PKCE they'd need the verifier, which never traveled through the browser.
- (c) The owner of another application registered with the same provider takes the ID token the victim gave them and presents it to us: it's authentic and signed, but it wasn't meant for us.
- (d) The attacker creates an account at the provider with the victim's email, without confirming it, and gets into the victim's AgendaViva account.
- (e) An open redirect at the end of a legitimate sign-in: the best moment to ask for something on a fake page.
Exercise 2: unlinking
Write the data function and the action that unlink the municipal ID. In what situation must it not be allowed?
Solution
// lib/data/external-accounts.ts — practice only
export async function unlinkIdentity(userId: string): Promise<boolean> {
const db = await getDb()
return db.transaction(async (tx) => {
const [user] = await tx
.select({ hash: users.passwordHash })
.from(users)
.where(eq(users.id, userId))
.for('update')
if (!user?.hash) return false // They'd be left with no way to sign in
await tx
.delete(externalAccounts)
.where(
and(
eq(externalAccounts.userId, userId),
eq(externalAccounts.provider, PROVIDER),
),
)
return true
})
}
// actions/account.ts
export async function unlinkAccount(): Promise<void> {
const user = await requireUser('/account')
if (await unlinkIdentity(user.id)) await endOtherSessions(user.id)
}It isn't allowed if it's the only way to sign in. The userId comes from the session, never from an argument. The other sessions are ended because one of them might have been opened with that identity, which is perhaps being unlinked precisely out of distrust.
Exercise 3: a second provider
The university also offers OIDC. Say what would change in the code and what security flaw would appear if both identities were stored by sub alone.
Solution
lib/env.ts: a list of providers by key (municipal,university) instead of a single object.lib/oidc.ts: aMapof configurations by key;startSignInreceives the key and stores it in the attempt. The callback uses the one in the attempt and never one from the URL: that way, a provider's response can't be made to validate against another.- Routes:
/api/sign-in/oidc/[provider], with the parameter checked against the list; and a differentredirect_uriper provider, which is the recommended defense against that mix-up. PROVIDERstops being a constant and becomes an argument.
sub is only unique within an issuer. Stored on its own, whoever obtained at the university the same sub that another person has at the city council would get into that person's account. With issuers that use sequential numbers, it could even happen by chance.
Conclusion
Signing in with an external provider means sending the person there with a challenge, a state and a nonce tied to their browser, redeeming the code server to server and validating the ID token. openid-client takes care of all that; our part is deciding which account it corresponds to, and the rule is to recognize by issuer and sub, accept only verified email addresses and never merge accounts without an open session. At the end, the same session from 08-01 is created, and the rest of the application doesn't notice the difference.
We now know who each person is, by two paths. We still don't ask what they can do: any account opens the dashboard. It's the gap we've put off most often and the one no library closes for us. It's closed in Authorization and the Data Access Layer.
