无效的JWT令牌导致500个内部服务器错误

时间:2019-02-22 18:07:12

标签: javascript node.js jwt hapijs

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

这是我的路线。我将处理程序请求中的有效负载传递到一个对我的密钥进行签名并返回令牌的插件:

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

        })
    }
};

然后我从邮递员访问我的路线,然后将包含电子邮件地址和密码的用户作为JSON传递回回合,这是我得到的响应:

{
    "statusCode": 401,
    "error": "Unauthorized",
    "message": "Missing authentication"
}

好的,这证明我的路线已成功受到保护。现在,我将令牌添加到Postman中:

enter image description here

然后我得到这个错误:

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

如果我从邮递员中删除令牌,则会收到“未经授权”错误。

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

当我将令牌粘贴到JWT.io中时,我可以在页面的右侧看到我的数据,但是JWT告诉我这是无效的签名。

我非常感谢您在这里提供一些说明。我正在使用hapi-auth-jwt2。

预先感谢

1 个答案:

答案 0 :(得分:1)

嗯,我正在向您发送另一条消息,但是随后我检查了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错误的详细信息。