Home > Mobile >  Why I can't decode jsonwebtoken in Node with Express?
Why I can't decode jsonwebtoken in Node with Express?

Time:04-29

I try to build an app in React with Express and I try to use JWT, but I can't verify what I encoded earlier.

This is how I created my jwt:

const secret = "grf1d2f1ee";

let token = jwt.sign({
            loggedIn: req.body.msg,
        },
            secret, { expiresIn: 60 * 60 }
        );

And this is the route where I try to check it:

app.post('/check', (req, res) => {
    const token = req.headers["authorization"];

    if (typeof token !== "undefined") {
        jwt.verify(token, secret, (err, decoded) => {
            if (err) {
                if (err.expiredAt) {
                    res.json({ message: "Your token expired!" });
                } else {
                    console.log(err);
                    res.json({ message: "Decoding error!" });
                }
            } else {
                res.json({ email: decoded.email })
            }
        });
    } else {
        res.json({ message: "Missing token!" });
    }
})

And this is where I sent data to be checked if is expired:

            let requestParam = globalRequestParameters;
            requestParam.method = 'POST';
            requestParam.headers.Authorization = check_loggedIn;
            requestParam.body = JSON.stringify(data_check);
            fetch(url   'check', requestParam)
                .then(res => res.json()
                    .then(res => {
                        console.log(res);
                    })
                )

My globalRequestParameters:

let globalRequestParameters = {
    method: "GET",
    mode: "cors",
    cache: "no-cache",
    credentials: "same-origin",
    headers: {
        "Content-Type": "application/json",
    },
    redirect: "follow",
    referrerPolicy: "no-referrer",
};

My error: JsonWebTokenError: invalid token

PROBLEM RESOLVED: I HAD TO PARSE THE TOKEN

CodePudding user response:

I can't be sure, I just don't have enough information, but it looks like you are referencing an undefined variable. You never actually give secret a value, but still use it as a function argument.

app.post('/check', (req, res) => {
    const token = req.headers["authorization"];

    console.log("Token value:")
    console.log(JSON.stringify(token))
    console.log("Headers value:")
    console.log(JSON.stringify(req.headers))
    if (typeof token !== "undefined") {
        //here you use the variabled "secret", but you never defined it
        jwt.verify(token, secret, (err, decoded) => {
            if (err) {
                if (err.expiredAt) {
                    res.json({ message: "Your token expired!" });
                } else {
                    console.log(err);
                    res.json({ message: "Decoding error!" });
                }
            } else {
                res.json({ email: decoded.email })
            }
        });
    } else {
        res.json({ message: "Missing token!" });
    }
})

If this isn't the problem, I'd recommend you add logging statements where I indicated and update your question with the results so that we can better understand what might be going wrong. @me in a comment when you do that and I'll try to update my answer.

  • Related