Skip to content

Instantly share code, notes, and snippets.

@antony
Last active January 16, 2022 16:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antony/0089ea3b23338abe44ffe01173416eb8 to your computer and use it in GitHub Desktop.
Save antony/0089ea3b23338abe44ffe01173416eb8 to your computer and use it in GitHub Desktop.
A very quick authentication server which validates a JWT
'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()
'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