Documentation / @zerotal/auth / BearerTokenMiddleware
Class: BearerTokenMiddleware
Defined in: auth/src/BearerTokenMiddleware.ts:46
Reads Authorization: Bearer <token> from the request, hashes it, looks the
matching TokenRow up via the registered loader, and — if the token is
found and unexpired — sets ctx.user and attaches a ctx.tokenCan(ability)
helper.
Remarks
This is a populate step, not a gate: it never rejects a request. An absent
or invalid token simply leaves ctx.user unset (guard the route separately with
AuthMiddleware), while a valid one also fires the optional setToucher hook
(fire-and-forget) to update last_used_at. The presented plaintext is SHA-256
hashed with hashToken before lookup — only hashes are compared, matching
how createToken stores them. Failed lookups emit a LoginFailed
framework event (invalid_token or expired_token).
Register a token loader once in a ServiceProvider:
Example
// In AuthProvider.onBooted():
BearerTokenMiddleware.setLoader(async (hash) => {
return PersonalAccessToken.query().where('token', hash).first();
});
// On routes that require API auth:
Router.group({ middleware: [BearerTokenMiddleware] }, () => {
Router.resource('posts', PostController);
});
// Check abilities in a controller:
if (!ctx.tokenCan('write')) {
ctx.response = Response.json({ message: 'Forbidden' }, { status: 403 });
return;
}
Extends
Constructors
Constructor
new BearerTokenMiddleware():
BearerTokenMiddleware
Defined in: core/src/middleware/BaseMiddleware.ts:36
Returns
BearerTokenMiddleware
Inherited from
Properties
options
protectedoptions:object={}
Defined in: auth/src/BearerTokenMiddleware.ts:47
Subclasses must declare this with their default option values. TypeScript enforces this at compile time — forgetting it is a type error.
Overrides
Methods
setLoader()
staticsetLoader(loader):void
Defined in: auth/src/BearerTokenMiddleware.ts:52
Parameters
loader
TokenLoader
Returns
void
setToucher()
staticsetToucher(toucher):void
Defined in: auth/src/BearerTokenMiddleware.ts:70
Register a callback that fires (fire-and-forget) after a valid token is used.
Use this to update last_used_at in the database.
Parameters
toucher
TokenToucher
Returns
void
Example
// In AuthProvider.onBooted():
BearerTokenMiddleware.setToucher(async (id) => {
await DB.table('personal_access_tokens')
.where('id', id)
.update({ last_used_at: new Date().toISOString() });
});
handle()
handle(
http,next):Promise<void|Response>
Defined in: auth/src/BearerTokenMiddleware.ts:74
Parameters
http
next
Returns
Promise<void | Response>
Overrides
with()
staticwith<T,Opts>(this,options): () =>InstanceType<T>
Defined in: core/src/middleware/BaseMiddleware.ts:48
Returns a zero-arg subclass with the given options deep-merged on top of the subclass defaults, usable directly in app.use([...]).
Type Parameters
T
T extends (...args) => BaseMiddleware<any>
Opts
Opts = T extends (...args) => BaseMiddleware<U> ? U : object
Parameters
this
T
options
Partial<Opts>
Returns
() => InstanceType<T>
Inherited from
afterResponse()?
optionalafterResponse(ctx):Promise<void>
Defined in: core/src/middleware/BaseMiddleware.ts:70
Parameters
ctx
Returns
Promise<void>
Inherited from
onError()?
optionalonError(ctx,error):Promise<void>
Defined in: core/src/middleware/BaseMiddleware.ts:71
Parameters
ctx
error
Error
Returns
Promise<void>