forked from hapi-swagger/hapi-swagger
-
Notifications
You must be signed in to change notification settings - Fork 1
/
jwt.js
122 lines (109 loc) · 2.41 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
// `jwt.js` - how to used in combination with JSON Web Tokens (JWT) `securityDefinition`
const Hapi = require('@hapi/hapi');
const jwt = require('jsonwebtoken');
const Blipp = require('blipp');
const Inert = require('@hapi/inert');
const Vision = require('@hapi/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 => {
// do your checks to see if the person is valid
if (!people[decoded.id]) {
return { isValid: false };
} else {
return { isValid: true };
}
};
const ser = async () => {
const server = Hapi.Server({
host: 'localhost',
port: 3000
});
await server.register([
require('hapi-auth-jwt2'),
Inert,
Vision,
Blipp,
{
plugin: HapiSwagger,
options: swaggerOptions
}
]);
server.auth.strategy('jwt', 'jwt', {
key: privateKey,
validate,
verifyOptions: { algorithms: ['HS256'] }
});
server.auth.default('jwt');
server.route([
{
method: 'GET',
path: '/',
options: {
auth: false,
handler: () => {
return { text: 'Token not required' };
}
}
},
{
method: 'GET',
path: '/restricted',
options: {
auth: 'jwt',
tags: ['api'],
handler: (request, h) => {
const response = h.response({
text: 'You used a Token! ' + request.auth.credentials.name
});
response.header('Authorization', request.headers.authorization);
return response;
}
}
},
{
method: 'GET',
path: '/token',
options: {
auth: false,
tags: ['api'],
handler: () => {
return { token: token };
}
}
}
]);
await server.start();
return server;
};
ser()
.then(server => {
console.log(`Server listening on ${server.info.uri}`);
})
.catch(err => {
console.error(err);
process.exit(1);
});