Skip to content

Instantly share code, notes, and snippets.

@pedroelsner
Created February 5, 2018 20:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedroelsner/b767b38151454bd69269e284dfc20efe to your computer and use it in GitHub Desktop.
Save pedroelsner/b767b38151454bd69269e284dfc20efe to your computer and use it in GitHub Desktop.
Hapi 17 + JWT
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);
});
{
"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