-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
91 lines (72 loc) · 1.99 KB
/
server.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
var Hapi = require('hapi'),
jwt = require('jsonwebtoken'),
server = new Hapi.Server();
server.connection({port: 8080});
var accounts = {
123: {
id: 123,
user: 'john',
fullName: 'John Doe',
scope: ['a', 'b']
}
};
var privateKey = 'BbZJjyoXAdr8BUZuiKKARWimKfrSmQ6fv8kZ7OFfc';
// Use this token to build your request with the 'Authorization' header.
// Ex:
// Authorization: Bearer <token>
var token = jwt.sign({accountId: 123}, privateKey, {algorithm: 'HS256'});
var validate = function (request, decodedToken, callback) {
var error,
credentials = accounts[decodedToken.accountId] || {};
if (!credentials) {
return callback(error, false, credentials);
}
return callback(error, true, credentials)
};
server.register(require('hapi-auth-jwt'), function (error) {
server.auth.strategy('token', 'jwt', {
key: privateKey,
validateFunc: validate,
verifyOptions: {algorithms: ['HS256']} // only allow HS256 algorithm
});
server.route({
method: 'GET',
path: '/token',
config: {
auth: false,
handler: function (request, reply) {
console.log('token');
reply({res: token});
}
}
});
server.route({
method: 'GET',
path: '/',
config: {
auth: 'token',
handler: function (request, reply) {
console.log('token');
reply({res: 'auth ok'});
}
}
});
// With scope requirements
server.route({
method: 'GET',
path: '/withScope',
config: {
auth: {
strategy: 'token',
scope: ['a']
},
handler: function (request, reply) {
console.log('token');
reply({res: 'ok'});
}
}
});
});
server.start(function () {
console.log('Servidor arrancado ', server.info.uri);
});