Introducing Sesame, an OAuth 2.1 and OpenID Connect server for AdonisJS
Your users want to connect other tools to your application. A partner integration, a CLI, a mobile app built by someone else, or more and more often, an AI agent talking to your API through MCP. None of them should ever see your users' passwords, each should only get the permissions the user approved, and the user should be able to cut access at any time.
That is what OAuth is for. And until now, running an OAuth server in AdonisJS meant building it yourself.
Today we're releasing @adonisjs/sesame, an OAuth 2.1 and OpenID Connect server for AdonisJS.
Why we built this
The access tokens guard works well when your own frontend or mobile app logs users in. It stops being enough as soon as third-party applications need to act on behalf of your users.
OAuth is not hard to understand, but it is easy to get subtly wrong. PKCE, redirect URI validation, refresh token rotation, replay detection, consent reuse, token revocation: each of these is a place where a small mistake becomes a security issue. We wanted a package that gets those details right, and stays out of the way for everything else.
Sesame does not own your users. You keep your user accounts, your login page, and your consent screen. Sesame adds the OAuth endpoints, stores clients, grants, and tokens in your database, and gives you an oauth auth guard to protect your API.
node ace add @adonisjs/sesame
node ace migration:run
What you get
Sesame follows OAuth 2.1, so the insecure parts of OAuth 2.0 are simply gone. There is no implicit grant, no password grant, and PKCE is mandatory for every client.
Out of the box, you get:
- The authorization code flow with mandatory S256 PKCE
- Refresh token rotation with replay detection
- Token introspection and revocation
- The client credentials grant for service-to-service calls
- Dynamic client registration and Client ID Metadata Documents
- OpenID Connect, with ID tokens, UserInfo, and discovery
- Opaque or JWT access tokens, with signing key rotation
- Resource indicators to bind tokens to a single API
Protecting your API
Add an oauth guard next to your session guard, then authenticate it on your routes. Scopes are inferred from your config, so a typo in a scope name is a type error.
router.get('/api/me', async ({ auth }) => {
const guard = auth.use('oauth')
const user = await guard.authenticate()
if (!guard.hasScope('read')) {
throw guard.insufficientScopeError(['read'])
}
return { id: user.id, clientId: guard.clientId }
})
A request without a valid token gets a 401, and a token without the scope gets a 403 with a WWW-Authenticate challenge telling the client which scopes it needs.
Your login and consent pages
Sesame never renders HTML. When an authorization request arrives, it sends the browser to your login page if the user is not logged in, then to your consent page when the requested scopes need approval. A user who already approved the same scopes skips the consent page.
You point Sesame to both pages in its config, next to the scopes and the descriptions your consent page displays.
const sesameConfig = defineConfig({
issuer: env.get('APP_URL'),
store: stores.lucid(),
scopes: {
read: 'Read access',
write: 'Write access',
},
defaultScopes: ['read'],
loginPage: '/login',
consentPage: '/oauth/consent',
})
Sesame forwards the authorization query parameters to your login page. After a successful login, send the browser back to /oauth/authorize with the same parameters, and the flow resumes where it stopped.
const query = request.input('authorization_query')
if (query) {
return response.redirect().toPath(`/oauth/authorize?${new URLSearchParams(query)}`)
}
The consent page receives an auth_token that identifies the pending authorization request. Load the request, then render the client name and the description of each requested scope.
export default class OAuthConsentController {
async show({ auth, request, response, view }: HttpContext) {
const user = await auth.authenticate()
const authToken = request.input('auth_token')
const pending = await sesame.findPendingAuthorizationRequest({
token: authToken,
userId: String(user.id),
})
if (!pending) {
return response.badRequest('Authorization request expired. Start again.')
}
const client = await sesame.findClient(pending.clientId)
if (!client) {
return response.badRequest('Client no longer exists')
}
return view.render('oauth/consent', {
authToken,
clientName: client.name,
scopes: pending.scopes.map((scope) => ({
name: scope,
description: sesame.config.scopes[scope] ?? scope,
})),
})
}
}
The client and the scopes always come from the stored request, never from the query string, so an attacker cannot make your consent screen display a trusted name or fewer permissions than the ones being granted.
The page itself is a regular form that posts the decision to the POST /oauth/consent endpoint Sesame registers. Sesame then redirects the browser to the client's callback.
<h1>Allow {{ clientName }} to access your account?</h1>
<ul>
@each(scope in scopes)
<li>{{ scope.description }}</li>
@end
</ul>
<form method="POST" action="/oauth/consent">
{{ csrfField() }}
<input type="hidden" name="auth_token" value="{{ authToken }}">
<button type="submit" name="accept" value="1">Allow</button>
<button type="submit">Deny</button>
</form>
To let the user approve only some permissions, submit a scope field with a subset of the requested scopes.
Need a team picker on the consent screen? Approve the request yourself and attach application context to the grant.
const { redirectUrl } = await sesame.approveAuthorization({
authToken: input.auth_token,
userId: String(user.id),
context: { teamId: authorizedTeamId },
})
return response.redirect().toPath(redirectUrl)
The guard exposes it on every authenticated request, as auth.use('oauth').context.
Grants, not just tokens
Every approval creates a grant. All the codes and tokens issued from that approval reference it, which gives you one handle to revoke everything a client obtained.
That makes the classic "connected applications" settings page a few lines of code:
const grants = await sesame.listGrants({ userId: String(user.id) })
await sesame.revokeGrant({ grantId, userId: String(user.id) })
Grants also power replay detection. If a stolen refresh token is used after it was rotated, Sesame revokes the whole grant, and every token issued from it stops working at once.
Built for MCP
MCP clients connect to your server without any manual setup: they discover your authorization server, identify themselves, run a PKCE authorization, and retry with a Bearer token. Sesame supplies every server-side piece of that flow:
- Protected resource metadata, so clients find your authorization server from a
401 - Resource audiences, so a token issued for your MCP server cannot be used on another API
- Scope challenges, so clients know which permissions to ask for
- Dynamic client registration and Client ID Metadata Documents, so clients can identify themselves without you creating them by hand
sesame.registerProtectedResource({
resource: '/api/mcp',
scopes: ['read', 'write'],
})
Coming from @julr/sesame?
Sesame started as @julr/sesame. It now lives under the AdonisJS organization as @adonisjs/sesame, and its documentation is part of the official AdonisJS docs. The package name is the only change: the API, configuration, commands, and database schema are the same. Follow the
migration guide
to switch.
What's next
This is version 0.11. Before 1.0, we are reviewing the public API one last time, so now is the best moment to try it and tell us what feels wrong.
Get started
node ace add @adonisjs/sesame
Read the OAuth server guide to set up your login and consent pages, and open an issue on GitHub if something does not work the way you expect.