Last active
January 16, 2022 16:35
-
-
Save antony/0089ea3b23338abe44ffe01173416eb8 to your computer and use it in GitHub Desktop.
A very quick authentication server which validates a JWT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
require = require('esm')(module) | |
const { init, shutdown } = require('./server.js') | |
async function bootstrap () { | |
const server = await init() | |
await server.start() | |
console.log(`Server running at: ${server.info.uri}`) | |
} | |
process.on('SIGINT', async () => { | |
await shutdown() | |
process.exit(0) | |
}) | |
bootstrap() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const Hapi = require('@hapi/hapi') | |
const HapiAuthJwt2 = require('hapi-auth-jwt2') | |
let server | |
exports.init = async () => { | |
server = Hapi.server({ | |
port: process.env.PORT || 3000, | |
host: '0.0.0.0', | |
debug: { request: ['error'] }, | |
routes: { | |
cors: { | |
credentials: true | |
} | |
}, | |
state: { | |
clearInvalid: true, | |
strictHeader: false | |
} | |
}) | |
await server.register([ | |
{ plugin: HapiAuthJwt2 } | |
]) | |
server.auth.strategy('jwt', 'jwt', { | |
cookieKey: 'my-auth', | |
key: 'abcde12345', | |
validate: ({ id}) => ({ | |
isValid: true, | |
credentials: { | |
id | |
} | |
}), | |
verifyOptions: { | |
algorithms: [ 'HS256' ] | |
} | |
}) | |
server.auth.default('jwt') | |
await server.initialize() | |
return server | |
} | |
exports.shutdown = async () => { | |
await server.stop({ timeout: 10000 }) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment