-
Notifications
You must be signed in to change notification settings - Fork 239
/
Copy pathserver.js
71 lines (66 loc) · 1.5 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
const Hapi = require('@hapi/hapi');
const jwt = require('hapi-auth-jwt2');
const jwksRsa = require('jwks-rsa');
const jwksHost = process.env.JWKS_HOST;
const audience = process.env.AUDIENCE;
const issuer = process.env.ISSUER;
// Fake validation, accept any authenticated user.
const validateUser = async (decoded) => {
console.log(decoded);
if (decoded && decoded.sub) {
return {
isValid: true
}
} else {
return {
isValid: false
}
}
};
const init = async () => {
// eslint-disable-next-line new-cap
const server = new Hapi.server({
port: 4001,
host: 'localhost'
});
await server.register(jwt);
// jwks-rsa strategy
server.auth.strategy('jwt', 'jwt', {
complete: true,
headerKey: 'authorization',
tokenType: 'Bearer',
key: jwksRsa.hapiJwt2KeyAsync({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 2,
jwksUri: `${jwksHost}/.well-known/jwks.json`
}),
validate: validateUser,
verifyOptions: {
audience: audience,
issuer: issuer,
algorithms: ['RS256']
}
});
server.auth.default('jwt');
server.route([
{
method: 'GET',
path: '/me',
config: { auth: 'jwt' },
handler: (request, h) => {
// This is the user object
return (request.auth.credentials)
}
}
]);
await server.start();
return server;
};
init()
.then(server => {
console.log(`Server running at: ${server.info.uri}`);
})
.catch(err => {
console.error(err);
});