hapi-oauth2-server-plugin
v0.4.0
Published
Hapijs wrapper for node oauth2-server package
Downloads
140
Maintainers
Readme
hapi-oauth2-server-plugin
Complete, compliant and well tested module for implementing an OAuth2 Server/Provider with hapi in node.js.
This is the hapi wrapper for oauth2-server.
Installation
$ npm install hapi-oauth2-server-plugin
Quick Start
The wrapper is actually a plugin for Hapi >= 17.
To use it you just need to register it like every Hapi plugin
const HapiOAuth2Server = require('hapi-oauth2-server-plugin');
...
server.register({
plugin: HapiOAuth2Server,
options: {
model
}
});
where model is a oauth2-server model object.
The plugin decorates Hapi requests with a oauth
object that contains the 3 oauth2-server main methods authenticate, authorize and token.
The methods accept an Hapi request object and an optional options object and return what the original and respective oauth2-server method provides.
Here follows a quick and easy example:
server.route({
method: 'GET',
path: '/authenticate',
config: {
handler: async (req, h) => {
const { oauth } = req.server.plugins['hapi-oauth-2-server']
try {
return await oauth.authenticate(req)
} catch (e) {
return h.response().code(401)
}
}
}
})
server.route({
method: 'GET',
path: '/authorize',
config: {
handler: async (req, h) => {
const { oauth } = req.server.plugins['hapi-oauth-2-server']
try {
return await oauth.authorize(req)
} catch (e) {
return h.response().code(401)
}
}
}
})
server.route({
method: 'POST',
path: '/token',
config: {
handler: async (req, h) => {
const { oauth } = req.server.plugins['hapi-oauth-2-server']
try {
return await oauth.token(req)
} catch (e) {
console.log(e)
return h.response().code(401)
}
}
}
})
Test
The repository offers also an out-of-the-box example and unit tests inside the test
folder.
What's next
Starting from this you can adapt it to your current authentication and authorization Hapi plugin or create your own by wrapping it as well in a new one.