forked from hapi-swagger/hapi-swagger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.js
123 lines (111 loc) · 3.34 KB
/
jwt.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// `jwt.js` - how to used in combination with JSON Web Tokens (JWT) `securityDefinition`
const Hapi = require('hapi');
const jwt = require('jsonwebtoken');
const Blipp = require('blipp');
const Inert = require('inert');
const Vision = require('vision');
const HapiSwagger = require('../');
let swaggerOptions = {
info: {
title: 'Test API Documentation',
description: 'This is a sample example of API documentation.'
},
securityDefinitions: {
jwt: {
type: 'apiKey',
name: 'Authorization',
in: 'header'
}
}
};
const people = {
// our "users database"
56732: {
id: 56732,
name: 'Jen Jones',
scope: ['a', 'b']
}
};
const privateKey = 'hapi hapi joi joi';
const token = jwt.sign({ id: 56732 }, privateKey, { algorithm: 'HS256' });
// bring your own validation function
const validate = (decoded, request, callback) => {
// do your checks to see if the person is valid
if (!people[decoded.id]) {
return callback(null, false);
}
return callback(null, true, people[decoded.id]);
};
const ser = async () => {
const server = new Hapi.Server({
host: 'localhost',
port: 3000
});
await server.register(
[
require('hapi-auth-jwt2'),
Inert,
Vision,
Blipp,
{
register: HapiSwagger,
options: swaggerOptions
}
],
err => {
if (err) {
console.log(err);
}
server.auth.strategy('jwt', 'jwt', {
key: privateKey, // Never Share your secret key
validateFunc: validate, // validate function defined above
verifyOptions: { algorithms: ['HS256'] } // pick a strong algorithm
});
server.auth.default('jwt');
server.route([
{
method: 'GET',
path: '/',
config: {
auth: false,
handler: function(request, reply) {
reply({ text: 'Token not required' });
}
}
},
{
method: 'GET',
path: '/restricted',
config: {
auth: 'jwt',
tags: ['api'],
handler: function(request, reply) {
reply({
text: 'You used a Token! ' + request.auth.credentials.name
}).header('Authorization', request.headers.authorization);
}
}
},
{
method: 'GET',
path: '/token',
config: {
auth: false,
tags: ['api'],
handler: function(request, reply) {
reply({ token: token });
}
}
}
]);
}
);
};
ser()
.then(server => {
console.log(`Server listening on ${server.info.uri}`);
})
.catch(err => {
console.error(err);
process.exit(1);
});