forked from ErickWendel/palestra-impacta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exemplo4-jwt2.js
72 lines (65 loc) · 1.8 KB
/
exemplo4-jwt2.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
'use strict';
const Hapi = require('hapi');
const jwt2 = require('hapi-auth-jwt2');
const JWT = require('jsonwebtoken');
const SECRET = 'NeverShareYourSecret';
const people = {
123: {
id: 1,
name: 'Jen Jones'
}
};
const validate = function (decoded, request, callback) {
if (!people[decoded.id]) return callback(null, false);
return callback(null, true);
};
var server = new Hapi.Server();
server.connection({ port: 8000 });
server.register(jwt2, () => {
server.auth.strategy('jwt', 'jwt',
{
key: SECRET,
validateFunc: validate,
verifyOptions: { algorithms: ['HS256'] }
});
server.auth.default('jwt');
server.route([
{
method: 'GET',
path: '/token',
config: {
auth: false
},
handler: (request, reply) => {
const obj = { id: 123, "name": "Charlie" }; // object/info you want to sign
const token = JWT.sign(obj, SECRET);
//new Buffer('partToken', 'base64').toString();
return reply(token);
}
},
{
method: "GET",
path: "/",
config: {
auth: false
},
handler: (request, reply) => {
reply({ text: 'Token not required' });
}
},
{
method: 'GET',
path: '/restricted',
config: {
auth: 'jwt'
},
handler: (request, reply) => {
reply({ text: 'You used a Token!' })
.header("Authorization", request.headers.authorization);
}
}
]);
});
server.start(function () {
console.log('Server running at:', server.info.uri);
});