forked from hapi-swagger/hapi-swagger
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjwt.js
More file actions
129 lines (116 loc) · 3.31 KB
/
Copy pathjwt.js
File metadata and controls
129 lines (116 loc) · 3.31 KB
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
124
125
126
127
128
129
'use strict';
// `jwt.js` - how to used in combination with JSON Web Tokens (JWT) `securityDefinition`
var Hapi = require('hapi');
var 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'
}
}
};
var people = {
// our "users database"
56732: {
id: 56732,
name: 'Jen Jones',
scope: ['a', 'b']
}
};
var privateKey = 'hapi hapi joi joi';
var token = jwt.sign({ id: 56732 }, privateKey, { algorithm: 'HS256' });
// bring your own validation function
var validate = function(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]);
};
var server = new Hapi.Server();
server.connection({
host: 'localhost',
port: 3000
});
server.register(
[
require('hapi-auth-jwt2'),
Inert,
Vision,
Blipp,
{
register: HapiSwagger,
options: swaggerOptions
}
],
function(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'],
plugins: {
'hapi-swagger': {
security: [{ jwt: [] }]
}
},
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 });
}
}
}
]);
}
);
server.start(function() {
console.log('Server running at:', server.info.uri);
});