Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS TypeError: Secret must be a string or buffer

Tags:

node.js

jwt

I'm using JWT's for authentication for a user login, but I always get following errors when I want to make a POST on /auth route.

(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.

Here is my 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);
});

Thanks for answers.

like image 389
pac Avatar asked Oct 20 '25 10:10

pac


1 Answers

The problem is you are not declared secret in config file. you can do it in another way

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

remove app.get('superSecretString') and add '123456'

like image 70
Carlos Avatar answered Oct 23 '25 02:10

Carlos