gpt4 book ai didi

javascript - 无效的 JWT token 导致 500 内部服务器错误

转载 作者:行者123 更新时间:2023-11-29 23:05:38 25 4
gpt4 key购买 nike

在服务器启动之前,所有插件等都已注册。我创建策略并将 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');

这是我的路线。我将来自处理程序请求的有效负载传递到一个插件中,该插件对我的 key 进行签名并返回一个 token :

'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']
}
});

}
};

这是我对 key 进行签名的方式:

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"
}

好的,这样就证明我的路由成功被保护了。我现在继续将我的 token 添加到 Postman 中:

enter image description here

然后我得到这个错误:

{
"statusCode": 500,
"error": "Internal Server Error",
"message": "An internal server error occurred"
}

如果我从 postman 那里删除 token ,我会收到“未经授权”的错误。

我想做的就是阻止外部访问我的 API,并且只允许有权限的人访问它。这将是注册的普通用户。

当我将我的 token 粘贴到 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 错误的详细信息。

关于javascript - 无效的 JWT token 导致 500 内部服务器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54832783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com