Created
February 5, 2018 20:07
-
-
Save pedroelsner/b767b38151454bd69269e284dfc20efe to your computer and use it in GitHub Desktop.
Hapi 17 + 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
const Hapi = require("hapi"); | |
const JWT = require("jsonwebtoken"); | |
// our "users database" | |
const people = { | |
1: { | |
id: 1, | |
name: "Jen Jones" | |
} | |
}; | |
// bring your own validation function | |
const validate = async (decoded, request) => { | |
if (!people[decoded.id]) { | |
return { isValid: false }; | |
} else { | |
return { isValid: true }; | |
} | |
}; | |
const init = async () => { | |
const server = new Hapi.Server({ port: 8000 }); | |
// include our module here ↓↓ | |
await server.register(require("hapi-auth-jwt2")); | |
server.auth.strategy("jwt", "jwt", { | |
key: "NeverShareYourSecret", | |
validate: validate, | |
verifyOptions: { algorithms: ["HS256"] } | |
}); | |
server.auth.default("jwt"); | |
server.route([ | |
{ | |
method: "GET", | |
path: "/", | |
options: { auth: false }, | |
handler: (request, h) => { | |
return { text: "Token not required. Get your in /token" }; | |
} | |
}, | |
{ | |
method: "GET", | |
path: "/token", | |
options: { auth: false }, | |
handler: (request, h) => { | |
let token = JWT.sign(people[1], "NeverShareYourSecret"); | |
let response = h.response({ | |
text: "Access with your token /restricted", | |
token: token | |
}); | |
response.header("Authorization", token); | |
return response; | |
} | |
}, | |
{ | |
method: "GET", | |
path: "/restricted", | |
options: { auth: "jwt" }, | |
handler: (request, h) => { | |
let response = h.response({ text: "You used a Token!" }); | |
response.header("Authorization", request.headers.authorization); | |
return response; | |
} | |
} | |
]); | |
await server.start(); | |
return server; | |
}; | |
init() | |
.then(server => { | |
console.log("Server running at:", server.info.uri); | |
}) | |
.catch(error => { | |
console.log(error); | |
}); |
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
{ | |
"name": "hapi17-jwt", | |
"version": "1.0.0", | |
"description": "", | |
"main": "index.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"hapi": "^17.2.0", | |
"hapi-auth-jwt2": "github:salzhrani/hapi-auth-jwt2#v-17", | |
"jsonwebtoken": "^8.1.1" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment