我刚刚开始学习hapi.js。我正在尝试理解身份验证的代码。这是如何工作的。为此,我关注了hapi-auth-jwt2。
之后,当我从邮递员那里调用 API 时,我没有得到任何输出。
这是我的server.js
文件,我运行node server.js
.
'use strict';
const Hapi = require('@hapi/hapi');
const jwt = require('jsonwebtoken');
const people = {
1: {
id: 1,
name: 'Jen Jones'
}
};
// bring your own validation function
const validate = async function (decoded, request, h) {
// do your checks to see if the person is valid
if (!people[decoded.id]) {
return { isValid: false };
}
else {
return { isValid: true };
}
};
const init = async () => {
const server = Hapi.server({
port: 3000,
host: 'localhost'
});
await server.register(require('hapi-auth-jwt2'));
server.auth.strategy('test', 'jwt',
{
key: 'GSFDSFJDSKGJD;GJRTWERIUEWFJDKL;GVCXVNMXCVCNVS;DLGFJKGFJDHGJFKHGJERHTKERHERJHTKREHJ', // Random String
validate,
verifyOptions: { algorithms: ['HS256'] }
});
server.auth.default('test');
server.route([
{
method: 'GET',
path: '/restricted',
config: {
auth: 'test'
},
handler: function (request, h) {
console.log("request.headers.authorization ::: ", request.headers.authorization);
const response = h.response({ text: 'You used a Token!' });
response.header("Authorization", request.headers.authorization);
return response;
}
}
]);
await server.start();
return server;
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init().then(server => {
console.log('Server running at:', server.info.uri);
})
.catch(err => {
console.log(err);
});
从邮递员