无效的 JWT 令牌导致 500 内部服务器错误
Invalid JWT token causes a 500 internal server error
服务器启动前,所有插件等都已注册。我创建策略并将 JWT 设置为服务器的默认身份验证方法。
await server.register(require('hapi-auth-jwt2'));
await server.register(require('~/utils/jwt-key-signer'));
server.auth.strategy(
'jwt', 'jwt',
{ key: process.env.API_KEY,
validate: true, // Temporarily using true
verifyOptions: { algorithms: [ 'HS256' ] }
});
server.auth.default('jwt');
这是我的路线。我将来自处理程序请求的有效负载传递到一个插件中,该插件签署了我的密钥和 returns 一个令牌:
'use strict';
const Boom = require('boom');
exports.plugin = {
name: 'user-create',
register: (server, options) => {
server.route({
method: 'POST',
path: '/user/create',
options: { auth: 'jwt' },
handler: async (request, h) => {
const { payload } = await request;
const { JWTKeySigner } = await server.plugins;
const token = await JWTKeySigner.signKeyReturnToken(payload);
const cookie_options = {
ttl: 365 * 24 * 60 * 60 * 1000, // expires a year from today
encoding: 'none', // we already used JWT to encode
isSecure: true, // warm & fuzzy feelings
isHttpOnly: true, // prevent client alteration
clearInvalid: false, // remove invalid cookies
strictHeader: true // don't allow violations of RFC 6265
}
return h.response({text: 'You have been authenticated!'}).header("Authorization", token).state("token", token, cookie_options);
},
options: {
description: 'Creates a user with an email and password',
notes: 'Returns created user',
tags: ['api']
}
});
}
};
以下是我对密钥进行签名的方式:
const jwt = require('jsonwebtoken');
exports.plugin = {
name: 'JWTKeySigner',
register: (server, options) => {
server.expose('signKeyReturnToken', async (payload) => {
jwt.sign(payload, process.env.API_KEY, { algorithm: 'HS256' }, async (err, token) => {
if (err) {
console.log(err)
}
await console.log(`TOKEN${token}`);
return token;
});
})
}
};
然后我从 Postman 访问我的路线,然后将包含电子邮件地址和密码的我的用户作为 JSON 传回回合,这是我得到的响应:
{
"statusCode": 401,
"error": "Unauthorized",
"message": "Missing authentication"
}
好的,这样就证明我的路由被成功保护了。我现在继续将我的令牌添加到 Postman 中:
然后我得到这个错误:
{
"statusCode": 500,
"error": "Internal Server Error",
"message": "An internal server error occurred"
}
如果我从邮递员那里删除令牌,我会收到 "unauthorised" 错误。
我想做的就是阻止外部访问我的 API,并且只允许有权限的人访问它。这将是注册的普通用户。
当我将令牌粘贴到 JWT.io 时,我可以在页面右侧看到我的数据,但 JWT 告诉我这是一个无效签名。
我真的很感激这里的一些清晰度。我正在使用 hapi-auth-jwt2.
提前致谢
嗯,我正在给你写另一条消息,但后来我检查了 hapi-auth-jwt2 文档的验证选项,它说;
validate - (required) the function which is run once the Token has been decoded with signature
async function(decoded, request, h) where:
decoded - (required) is the decoded and verified JWT received in the request
request - (required) is the original request received from the client
h - (required) the response toolkit.
Returns an object { isValid, credentials, response } where:
isValid - true if the JWT was valid, otherwise false.
credentials - (optional) alternative credentials to be set instead of decoded.
response - (optional) If provided will be used immediately as a takeover response.
试试
server.auth.strategy(
'jwt', 'jwt',
{ key: process.env.API_KEY,
validate: validate: () => ({isValid: true}), // Temporarily using true
verifyOptions: { algorithms: [ 'HS256' ] }
});
那我们看看500错误是否继续。
也许您的代码中的其他一些东西引发了错误。您是否在服务器设置上启用了调试?您应该会在服务器控制台中看到该 500 错误的详细信息。
服务器启动前,所有插件等都已注册。我创建策略并将 JWT 设置为服务器的默认身份验证方法。
await server.register(require('hapi-auth-jwt2'));
await server.register(require('~/utils/jwt-key-signer'));
server.auth.strategy(
'jwt', 'jwt',
{ key: process.env.API_KEY,
validate: true, // Temporarily using true
verifyOptions: { algorithms: [ 'HS256' ] }
});
server.auth.default('jwt');
这是我的路线。我将来自处理程序请求的有效负载传递到一个插件中,该插件签署了我的密钥和 returns 一个令牌:
'use strict';
const Boom = require('boom');
exports.plugin = {
name: 'user-create',
register: (server, options) => {
server.route({
method: 'POST',
path: '/user/create',
options: { auth: 'jwt' },
handler: async (request, h) => {
const { payload } = await request;
const { JWTKeySigner } = await server.plugins;
const token = await JWTKeySigner.signKeyReturnToken(payload);
const cookie_options = {
ttl: 365 * 24 * 60 * 60 * 1000, // expires a year from today
encoding: 'none', // we already used JWT to encode
isSecure: true, // warm & fuzzy feelings
isHttpOnly: true, // prevent client alteration
clearInvalid: false, // remove invalid cookies
strictHeader: true // don't allow violations of RFC 6265
}
return h.response({text: 'You have been authenticated!'}).header("Authorization", token).state("token", token, cookie_options);
},
options: {
description: 'Creates a user with an email and password',
notes: 'Returns created user',
tags: ['api']
}
});
}
};
以下是我对密钥进行签名的方式:
const jwt = require('jsonwebtoken');
exports.plugin = {
name: 'JWTKeySigner',
register: (server, options) => {
server.expose('signKeyReturnToken', async (payload) => {
jwt.sign(payload, process.env.API_KEY, { algorithm: 'HS256' }, async (err, token) => {
if (err) {
console.log(err)
}
await console.log(`TOKEN${token}`);
return token;
});
})
}
};
然后我从 Postman 访问我的路线,然后将包含电子邮件地址和密码的我的用户作为 JSON 传回回合,这是我得到的响应:
{
"statusCode": 401,
"error": "Unauthorized",
"message": "Missing authentication"
}
好的,这样就证明我的路由被成功保护了。我现在继续将我的令牌添加到 Postman 中:
然后我得到这个错误:
{
"statusCode": 500,
"error": "Internal Server Error",
"message": "An internal server error occurred"
}
如果我从邮递员那里删除令牌,我会收到 "unauthorised" 错误。
我想做的就是阻止外部访问我的 API,并且只允许有权限的人访问它。这将是注册的普通用户。
当我将令牌粘贴到 JWT.io 时,我可以在页面右侧看到我的数据,但 JWT 告诉我这是一个无效签名。
我真的很感激这里的一些清晰度。我正在使用 hapi-auth-jwt2.
提前致谢
嗯,我正在给你写另一条消息,但后来我检查了 hapi-auth-jwt2 文档的验证选项,它说;
validate - (required) the function which is run once the Token has been decoded with signature
async function(decoded, request, h) where:
decoded - (required) is the decoded and verified JWT received in the request
request - (required) is the original request received from the client
h - (required) the response toolkit.
Returns an object { isValid, credentials, response } where:
isValid - true if the JWT was valid, otherwise false.
credentials - (optional) alternative credentials to be set instead of decoded.
response - (optional) If provided will be used immediately as a takeover response.
试试
server.auth.strategy(
'jwt', 'jwt',
{ key: process.env.API_KEY,
validate: validate: () => ({isValid: true}), // Temporarily using true
verifyOptions: { algorithms: [ 'HS256' ] }
});
那我们看看500错误是否继续。
也许您的代码中的其他一些东西引发了错误。您是否在服务器设置上启用了调试?您应该会在服务器控制台中看到该 500 错误的详细信息。