Authentication
The server accepts three kinds of credentials on every secured route. Each one can be switched off by configuration:
| Kind | Header | Setting |
|---|---|---|
Bearer token (from POST /auth/login) | Authorization: Bearer <token> | AUTH_BEARER |
| API key of a user | X-AUTH-APIKEY: <key> | AUTH_TOKEN |
| Basic auth | Authorization: Basic <base64> | AUTH_BASIC |
Browser sessions
useMongocampAuth() logs in with user and password and stores the token and the profile in the cookie mongocamp-session. The cookie is SameSite=Lax, and Secure outside of dev. It is readable during SSR, so pages render as the logged-in user.
const { login, logout, isLoggedIn, isAuthenticated, userRoles, userGrants } = useMongocampAuth()
const profile = await login('alice', 'secret') // UserProfile: user, isAdmin, roles, grants, apiKey
isLoggedIn.value // true
userRoles.value // ['editor']
await isAuthenticated() // asks the server whether the token is still valid
logout() // revokes the token on the server and clears the cookieWith
refreshToken: true, a single interval per session callsGET /auth/token/refresheverytokenRefreshIntervalms and stores the new token. A401or403on refresh logs out.After a refresh the old token stays valid for
AUTH_REFRESH_GRACE_DURATION(default 60 s), so requests already in flight still succeed.Any
401from any API call clears the session. A403(a missing grant) leaves the session alone.With sessions (
AUTH_SESSIONS, 3.0) the refresh uses the httpOnly refresh cookie of the server and rotates it; this needs the API on the same origin (the embedded server, or a proxy).
useMongocampUser() gives the current profile as a read-only ref, and useMongocampStorage() gives the raw cookie ref ({ token, profile, session? }).
Registration, verification, reset, login links, sessions (3.0)
The flows the server switched on (Authentication on the server) are part of useMongocampAuth():
const auth = useMongocampAuth()
await auth.register({ email: 'ada@example.org', password: 'secret-1', displayName: 'Ada' }) // AUTH_REGISTRATION
await auth.verifyEmail(route.query.token as string) // the page of the verification link (/verify-email)
await auth.requestEmailVerification('ada@example.org')
await auth.requestPasswordReset('ada@example.org') // AUTH_PASSWORD_RESET
await auth.resetPassword(route.query.token as string, 'secret-2') // the page of the reset link (/reset-password)
await auth.requestLoginLink('ada@example.org') // AUTH_PASSWORDLESS
await auth.loginWithLink({ token: route.query.token as string }) // the page of the link (/login-link), logs in
await auth.loginWithLink({ email: 'ada@example.org', code: '123456' }) // or the code of the mail
const sessions = await auth.sessions() // AUTH_SESSIONS: { id, userAgent, ip, lastUsedAt, current }[]
await auth.revokeSession(sessions[1].id)
await auth.revokeAllSessions() // logout everywhere, this one tooEach call throws a MongocampRequestError on an error answer (status, code: 4403 for a used or expired link, 4035 for an unverified address); a flow the server did not switch on answers 404. The requests of registration, reset and login link answer the same whether or not the address is known.
Protecting pages
A minimal route middleware:
// middleware/auth.ts
export default defineNuxtRouteMiddleware((to) => {
const { isLoggedIn } = useMongocampAuth()
if (!isLoggedIn.value && to.path !== '/login')
return navigateTo('/login')
})Server code with an API key
In server routes, useMongocampEventApi(event) (before 2.8 useMongocampApi(event)) authenticates with the module's apiKey option. If no key is set, it uses the token you pass as the second argument:
// server/api/report.get.ts
import { defineHandler } from 'nitro'
export default defineHandler(async (event) => {
const { documentApi } = useMongocampEventApi(event)
return documentApi.listDocuments({ collectionName: 'orders', filter: 'status:open', rowsPerPage: 100 })
})Create the technical user with an API key once, e.g. in the admin UI or with PATCH /admin/users/{userId}/apikey. Then set NUXT_MONGOCAMP_API_KEY.
Acting for a user
Since 2.7.0 an administrator can send a request for another user with the header X-AUTH-ACT-AS: <userId> (ActAsHeader of the core). It is meant for a trusted backend — server routes that check their own rules and call MongoCamp with an administrator API key — that still wants the behaviours of declared collections to work per user:
- the rights stay the administrator's: the users need no grants, and the generic API stays closed to them;
- the behaviours (
ownerscopes and 404 for foreign documents,timestampsusers,versioned,audit), the read scopes and the document events see the acting user;adminBypassdoes not apply, because that user is no administrator; - the events and interceptor payloads carry the administrator as
actedBy, and so do the audit records (3.1.1); - what bypasses the read scopes is decided by the acting user (3.1.1): the history of a document it cannot read (404), the history of a collection,
withDeleted, copy and clear of a restricted collection and the files collections of a protected bucket (403) — unless that user is an administrator of the collection itself.
A caller that is no administrator gets 403, an unknown user 401; an empty header is ignored. The header is not in the default CORS_HEADERS_ALLOWED: browsers are not meant to send it.
Since 2.8.0 such a backend can also send X-MONGOCAMP-KEEP-TIMESTAMPS: true for maintenance writes: on collections with timestamps.preserveOnUpdate the updatedAt / updatedBy it sends are kept. Without the header every write is stamped as usual; for callers that are no administrators it has no effect.
// server/utils/data.ts: as the user of the request, through the module's server client with the api key
const fetchApi = (input: RequestInfo | URL, init?: RequestInit) => {
const request = new Request(input, init)
request.headers.set('X-AUTH-ACT-AS', currentUser)
return fetch(request)
}
const { documentApi } = useMongocampServerApi(url, apiKey, undefined, fetchApi)Users, roles and grants
- Users have a password, an optional API key and a list of roles.
- Roles carry grants: per collection or bucket a
read,writeandadministrateflag. A role can beisAdmin, which allows everything. - Grant names match case-insensitively and support the
*wildcard. GET /auth/permissionstells a client what the user may do (see Users, Tokens & Grants).
With AUTH_HANDLER=mongo (default) users and roles live in mc_users and mc_roles and are managed through /admin/* (useMongocampApiAdmin()). With AUTH_HANDLER=static they come from AUTH_USERS and AUTH_ROLES:
AUTH_HANDLER=static
AUTH_USERS='[{"userId":"admin","password":"secret","roles":["admin"]},{"userId":"reader","password":"secret","roles":["reader"],"apiKey":"key-1"}]'
AUTH_ROLES='[{"name":"admin","isAdmin":true,"collectionGrants":[]},{"name":"reader","isAdmin":false,"collectionGrants":[{"name":"books","read":true,"write":false,"administrate":false,"grantType":"COLLECTION"}]}]'Each entry can be a JSON object or a JSON string holding one. grantType is COLLECTION (default), BUCKET or BUCKET_META. Passwords can be plain text or a hash in the new scrypt format.
Missing grants: 403
A logged-in user without the grant for a collection gets the status of AUTH_GRANT_DENIED_STATUS, 403 by default, so the session stays. AUTH_GRANT_DENIED_STATUS=401 restores the behaviour before 2.1, where the client clears the session.
