fastify-auth-scheme
Inspired by hapi authenticatio flow, this plugin brings allows to register authentication strageties in your fastify server, define a default strategy that will be applied to all routes and allows overriding the default at the route.
This plugin doesn't implement any authentication strategies though, that's up to you to define.
Usage
To use fastify-auth-scheme
you need to register it in your fastify instance and add some auth strategies, like so:
;; ;server.registerfastifyAuthScheme; server.auth.addStrategy"my-auth-strategy", ; // register default strategy for all routesserver.auth.setDefault"my-auth-strategy"; // register your routesserver.get"/", ; // route level configuration of auth - this route will no require authenticationserver.get"/no-auth", , ;
Auth Strategy API
To register a new strategy, you need to give it a unique name and a function to handle the authentication.
The authentication function must take in the request
and reply
objects from fastify and return
After you register a strategy, you can make it default by calling server.auth.setDefault(<auth name>)
. This will apply the default auth strategy to all routes that don't have an override config.
Route level configuration
You can define route-level authentication by passing a config object to the route, like so:
server.get"/", , routeHandler;
The AuthConfig is one of:
false
: this disables authentication for this route, preventing default authentication strategy from being applied"try"
: this option will still run the default strategy (if registered) and will set the user credentials in the request if authentication succeeds, but it will not prevent access to the route if authentication fails (in which case the request.auth will be null).<strategy name>
: by passing a strategy name toauth
config, you can override the default auth scheme and use a specific one to a given route.
If nothing is passed to auth config, the default auth will be used.
LICENSE
MIT License
Copyright (C) 2020 Vinicius Teixeira vinicius0026@gmail.com