node.js - Node JS 类型错误 : Secret must be a string or buffer

标签 node.js jwt

我使用 JWT 进行用户登录身份验证,但当我想在 /auth 路由上进行 POST 时,我总是收到以下错误。

(node:3385) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: secret must be a string or buffer

(node:3385) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

这是我的代码

app.post('/auth', function (req, res, next) {
    var username = req.body.username;
    var password = req.body.password;

    User.findOne({
        where: {username: username}
    }).then(function (user) {
        if(user){
            bcrypt.compare(req.body.password, user.password).then(function (passcheck) {
                if(passcheck){
                    var jwtUser = {
                        username: user.username,
                        name: user.name,
                        score: user.score,
                        accesslevel: "all"
                    };

                    var token = jwt.sign(jwtUser, app.get('superSecretString'), {
                        expiresIn: 1440 //expires in 24 hours
                    });

                    //callback(token);

                    res.json({
                        success: true,
                        message: 'Here´s your token.',
                        token: token
                    });

                    /*
                    var resp = {success: true, message: 'Heres your token.', token: token};
                    response.write(JSON.stringify(resp));
                    */
                }else{
                    res.status(401).json({
                        success: false,
                        message: 'Authentification failed. Password or Username wrong'
                    });
                }
            });
        }else{
            res.status(401).json({
                success: false,
                message: 'Authentification failed.'
            });
        }
    }).catch(next);
});

感谢您的回答。

最佳答案

问题是您没有在配置文件中声明 secret 。 你可以用另一种方式做到这一点

const token = jwt.sign(user, '123456', {
                    expiresIn: 60 * 24 // expires in 24 hours
                });

删除 app.get('superSecretString') 并添加 '123456'

关于node.js - Node JS 类型错误 : Secret must be a string or buffer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44133496/

相关文章:

asp.net-core - asp.net core WEB API 中的身份验证和授权

cryptography - 验证 jwt token [rsa]

java - 为什么我的自定义 AuthenticationProvider 无法抛出或处理 BadCredentialsException?

javascript - Node如何在使用pug和express Node网站单击按钮时运行python脚本

javascript - 使用 mysql 对discord.js 进行排名

node.js - 总是在 jwt.io 中得到无效签名

java - 如何在 JWT Filter 中将 api 列入白名单

javascript - 从嵌套对象和数组的巨大 JSON 中以编程方式解构特定属性的最佳且最有效的方法

javascript - 带有 oAuth 重定向的 Electron 自定义协议(protocol)

http - 哪个 node.js HTTP 代理实现性能更高?