Users, Tokens & Grants
See Authentication for the client side.
Tokens
POST /auth/login issues a signed token (JWT). Its claims are user and isAdmin (plus exp, iat, jti, iss). Roles, grants and the API key are not in the token, so its size does not grow with the grants. The server resolves them on every request.
GET /auth/token/refreshissues a new token. The old one stays valid forAUTH_REFRESH_GRACE_DURATION(default 60 s) for concurrent requests, then it is revoked. A call with Basic auth or an API key revokes nothing.POST /auth/logoutrevokes the token.- With
AUTH_CACHE_DB(default) tokens are stored as SHA-256 hashes inmc_token_cache. Reading that collection does not give usable tokens.
Changes to a user apply to tokens that were already issued (mongo handler):
- A new password revokes all tokens of the user.
PATCH /auth/profile/passwordkeeps the token used for the call, so the user stays logged in and the other sessions end. - Deleting a user revokes all of their tokens. A token of a deleted user answers
401. - New roles, changed grants and a new API key apply immediately.
Passwords
Passwords are stored as salted scrypt hashes. Hashes of older servers are replaced at the next successful login (see Migration to 2.0). Basic auth remembers a verified password for 60 seconds while the stored hash is unchanged.
The first administrator
With the mongo handler and no users, the server creates the user admin (role adminRole) with a random password at startup and prints the password to the log.
Sessions with refresh rotation (3.0, opt-in)
With AUTH_SESSIONS=true a login also opens a session: the answer has refreshExpirationDate and sessionId, and the refresh token is set as an httpOnly cookie (mongocamp_refresh, SameSite=Strict, for the auth routes only, Secure on https). The refresh token is never in an answer for a browser, so a script on the page cannot read it; a client without cookies sends the header x-mongocamp-refresh-token: body to get refreshToken in the body, and a refresh with the token in its body answers the next one in the body. The access token is the same as without sessions (AUTH_EXPIRING_DURATION). Without the setting, nothing changes: no field, no cookie, no route.
| Route | |
|---|---|
POST /auth/refresh-token | exchanges the refresh token (body refreshToken, or the cookie) for a new access token and a new refresh token |
GET /auth/sessions | the active sessions of the user (userAgent, ip, lastUsedAt, current) |
DELETE /auth/sessions/{id} | ends one session and its access tokens |
DELETE /auth/sessions | ends all sessions of the user (logout everywhere) |
- A refresh token works once. A token that was exchanged before is a stolen copy: the session and its access tokens are revoked (
401, code4014). The previous token withinAUTH_REFRESH_GRACE_DURATIONis no reuse (two tabs refresh at once): it gets an access token, the refresh token stays the newer one. - Logout ends the session of its token; a new password ends the other sessions, an administrator's new password, disabling or deleting a user end all of them.
- The database holds the SHA-256 of the refresh tokens (
mc_sessions, removed a day after they expire). A revoked session ends its access tokens at once on this instance, on others within the 5 minutes of their memory copy. AUTH_SESSION_DURATION(default30d) is the lifetime of a session.- The Nuxt module uses the cookie for its token refresh when the login answered a session (same origin: the embedded server or a proxy); otherwise it refreshes as in 2.x.
Registration, verification, password reset (3.0, opt-in)
Off by default (no routes). Users of the database (AUTH_HANDLER=mongo) only.
| Setting | |
|---|---|
AUTH_REGISTRATION | off (default), open: anyone registers with an e-mail address and gets a verification mail; invite: only with the token of an invitation (POST /auth/invite, administrators), the address counts as verified and the user gets the roles of the invitation |
AUTH_REGISTRATION_ROLES | roles of an open registration (default none) |
AUTH_REQUIRE_VERIFIED_EMAIL | true: a user with an unverified address cannot log in (403, code 4035); users without an address are not affected |
AUTH_PASSWORD_RESET | true: POST /auth/request-password-reset and POST /auth/reset-password |
AUTH_PASSWORD_MIN_LENGTH | default 8, for registration and reset |
AUTH_APP_URL | the base of the links in the mails (/verify-email, /reset-password, /register with ?token=); default the origin of the request |
AUTH_VERIFY_DURATION, AUTH_RESET_DURATION, AUTH_INVITE_DURATION | 24h, 1h, 7d |
POST /auth/register{ email, password, userId?, displayName?, inviteToken? }answers202whether or not the address or user id exists (an existing one gets nothing); so dorequest-verificationandrequest-password-reset. Known and unknown addresses take the same time.- Tokens are single-use and expire; the database holds their SHA-256 (
mc_auth_tokens, TTL). A used, expired or unknown token answers400(code4403). A reset ends every token and session of the user. - At most one mail of a kind per address and minute.
Passwordless login (3.0, opt-in)
AUTH_PASSWORDLESS=true: POST /auth/passwordless/request { email } (always 202) mails a login link (AUTH_APP_URL/login-link?token=…) and a 6-digit code to the user with this address. POST /auth/passwordless/login takes { token } (the link) or { email, code } and answers like a login (with a session when AUTH_SESSIONS is on). Link and code are one token: the first use ends both; after 5 wrong codes it ends too, and with RATE_LIMIT_LOGIN wrong codes count as failed logins of the address. The code of one user never works for another. The login verifies the address. AUTH_PASSWORDLESS_DURATION (default 15m) is the lifetime; one mail per address and minute.
Sending the mails
The server sends no mail. Each mail is the event auth:mail with { kind: 'verify' | 'reset' | 'invite' | 'magic', to, url, token, code?, expiresAt, user? } — a Nitro hook mongocamp:auth:mail in a Nuxt app, server.events.on('auth:mail', ...) standalone. Without a listener the server logs a warning once.
// server/plugins/auth-mail.ts with nodemailer
import { definePlugin } from 'nitro'
import nodemailer from 'nodemailer'
const transport = nodemailer.createTransport(process.env.SMTP_URL)
const subjects = { verify: 'Confirm your address', reset: 'Reset your password', invite: 'You are invited', magic: 'Your login link' }
export default definePlugin((nitroApp) => {
nitroApp.hooks.hook('mongocamp:auth:mail', async (mail) => {
await transport.sendMail({ from: 'app@example.org', to: mail.to, subject: subjects[mail.kind], text: `${mail.url}${mail.code ? `\n\nCode: ${mail.code}` : ''}` })
})
})// with Resend
import { Resend } from 'resend'
const resend = new Resend(process.env.RESEND_API_KEY)
nitroApp.hooks.hook('mongocamp:auth:mail', async (mail) => {
await resend.emails.send({ from: 'app@example.org', to: mail.to, subject: mail.kind, html: `<a href="${mail.url}">${mail.url}</a>` })
})The hook is not awaited by the answer (so its time tells nothing); a failure is logged.
User fields (3.0)
Besides userId, password, apiKey and roles, a user may have email, emailVerified, displayName, linked identities ({ provider, subject } of other login providers, kept for a later feature; no OAuth login in 3.0) and disabled; the server records lastLoginAt on each login. Users without these fields work as before, no data migration is needed.
emailis unique among the users that have one (stored trimmed and in lower case; a duplicate answers409, code4093). The unique indexes are partial: only documents with the field are indexed.disabled: trueblocks the user: no login, and Basic auth and its api key answer401(code4013; a login with the right password too). Disabling revokes its tokens, so a token issued before answers401with code4011(invalid token).PUT /admin/usersaccepts the fields,PATCH /admin/users/{userId}changesemail,emailVerified,displayNameanddisabled(nullremovesemailordisplayName). The profile answers include them when the user has them.PATCH /auth/profile(3.1.0,authApi.updateProfile) lets a logged-in user change its owndisplayName(nullremoves it); every other field stays with the administrator.- The static handler reads them from
AUTH_USERS.
Permissions
3.0: * does not reach the server's own collections
A * grant (collection, bucket or *.files) does not match the internal collections and buckets: names with the AUTH_PREFIX (mc_users, mc_roles, mc_configuration, mc_audit, the backups bucket mc_backups, ...), system.*, the .files / .chunks collections of buckets and the .variants buckets of image variants. Only a grant that names them, or an administrator, reaches them. In 2.x a * grant did.
GET /auth/permissions returns what the logged-in user may do, with the same matching that protects the routes (case-insensitive names, the * wildcard, admins may do everything):
[{ "name": "accounts", "read": true, "write": true, "administrate": false }]Without a parameter it lists the collections of the default database with at least one right. ?collection=name answers exactly that collection, with all flags false if the user has no right. The collection lists use the same matching, so a listed collection can be opened.
| Grant | Allows |
|---|---|
read | list, get, search, count, aggregate, export, fields/schema |
write | insert, update, delete, import, clear |
administrate | create, drop, rename, change options, indexes |
Missing grants
A logged-in user without the grant gets AUTH_GRANT_DENIED_STATUS: 403 by default (error code 4011), so the user keeps the session. Set it to 401 for the behaviour before 2.1, where the clients clear the session. A missing or invalid token is always 401.
