Checking access
On this page
This guide covers the Access class for checking permissions at runtime. You will learn how to:
- Create an Access instance from a user or raw permission keys
- Check whether a permission is allowed or denied
- Scope permissions for API tokens
Overview
Section titled "Overview"The Access class represents the resolved set of permissions for a specific user in a specific context. It takes raw permission strings (from the database), resolves aliases, removes inactive and unknown keys, and provides allows and denies methods for checking access.
You do not create Access instances directly. Instead, use the createAccess or createAccessFor methods on your Permissions instance.
Creating an Access instance
Section titled "Creating an Access instance"From a user
Section titled "From a user"The most common approach is createAccessFor, which loads the user's permissions (from roles and direct assignments) and resolves them in one step.
import { permissions } from '#start/permissions'
const access = await permissions.createAccessFor(user)
access.allows('product.create') // true or falseThe user must implement a getPermissions() method that returns a Promise<string[]>. Both the withRoles and withPermissions mixins provide this method.
Warning
createAccessFor keeps the Access on the model instance and returns it on every later call. After you change a user's roles or permissions, fetch the user again (await User.findOrFail(user.id)) before you check access.
From raw keys
Section titled "From raw keys"For lower-level control, create an empty Access instance and populate it manually.
const rawAccess = permissions.createAccess()
rawAccess.use(['product.create', 'product.update', 'product.remove'])The use method resolves aliases and filters out inactive and unknown keys before adding them to the resolved set.
Checking permissions
Section titled "Checking permissions"access.allows('product.create') // true
access.denies('billing.refund') // trueBoth methods accept a permission key and return a boolean. Keys are type-safe and will be autocompleted by your editor.
Listing permissions
Section titled "Listing permissions"Use the permissions method to get all resolved permission keys.
access.permissions()
// ['product.create', 'product.update', 'product.delete']Token scoping
Section titled "Token scoping"When issuing API tokens, you may want to limit the token's capabilities to a subset of the user's permissions. The scopeTo method intersects the resolved permissions with the provided abilities, keeping only permissions present in both.
const scopedAccess = await permissions.createAccessFor(user)
// User has: product.create, product.update, product.delete, billing.refund
// Token allows: product.create, product.update
scopedAccess.scopeTo(['product.create', 'product.update'])
scopedAccess.allows('product.create') // true
scopedAccess.allows('product.delete') // false (not in token scope)
scopedAccess.allows('billing.refund') // false (not in token scope)A token with * keeps the full set of the user's active permissions. It does not grant a permission that the user lacks. A scoped Access stays narrowed on that model instance for the rest of the request.
scopeTo resolves the aliases in the token's list and drops inactive and unknown keys.
Authorizing routes
Section titled "Authorizing routes"The authorize middleware checks a permission before the route's controller runs. Pass one key, or an array of keys to let in users who hold any of them. A guest, or a user without the permission, gets a 403.
import router from '@adonisjs/core/services/router'
import { middleware } from '#start/kernel'
import { controllers } from '#generated/controllers'
router
.delete('/products/:id', [controllers.Products, 'destroy'])
.use(middleware.authorize('product.delete'))
router
.put('/products/:id', [controllers.Products, 'update'])
.use(middleware.authorize(['product.update', 'product.delete']))To change the error, override createAccessDeniedResponse in app/middleware/authorize_middleware.ts.
import AuthorizeMiddleware from '#middleware/authorize_middleware'
import { AuthorizationResponse } from '@adonisjs/bouncer'
export default class CustomAuthorizeMiddleware extends AuthorizeMiddleware {
protected createAccessDeniedResponse() {
return AuthorizationResponse.deny('You cannot do this', 403)
}
}
With access tokens
Section titled "With access tokens"When your app signs users in with access tokens, scope the Access by the token in app/middleware/authorize_middleware.ts. Add the check after createAccessFor(user) in the generated middleware.
import type { HttpContext } from '@adonisjs/core/http'
import type { NextFn } from '@adonisjs/core/types/http'
import { AuthorizationResponse, errors } from '@adonisjs/bouncer'
import { permissions, type PermissionKey } from '#start/permissions'
export default class AuthorizeMiddleware {
protected createAccessDeniedResponse() {
return AuthorizationResponse.deny('Access denied', 403)
}
async handle(ctx: HttpContext, next: NextFn, ability: PermissionKey | PermissionKey[]) {
const user = ctx.auth.user
if (!user) {
throw new errors.E_AUTHORIZATION_FAILURE(this.createAccessDeniedResponse())
}
const access = await permissions.createAccessFor(user)
if (user.currentAccessToken) {
access.scopeTo(user.currentAccessToken.abilities)
}
const allowed = Array.isArray(ability)
? ability.some((a) => access.allows(a))
: access.allows(ability)
if (!allowed) {
throw new errors.E_AUTHORIZATION_FAILURE(this.createAccessDeniedResponse())
}
return next()
}
}
The Access is stored on the user. Bouncer and every later check of the request see the token's set. Your User model declares currentAccessToken?: AccessToken, with AccessToken imported from @adonisjs/auth/access_tokens, as the API starter kit does.
Give each token the abilities it needs.
const token = await User.accessTokens.create(user, [permissions.getKey('product.create')])Reference
Section titled "Reference"use(rawKeys: string[]) => voidallows(key: PermissionKey) => booleantrue when the key is in the set.denies(key: PermissionKey) => booleantrue when the key is not in the set.scopeTo(abilities: string[]) => voidabilities. A list with * leaves the set unchanged.permissions() => PermissionKey[]