0
votes

I'm trying to use JWT to protect a post route in my nodejs, express, react application. I tested it using postman by adding the JWT token to the headers and works perfectly to add the user to the database. But if I do the request from react using axios I get a 401 response (Unauthorized).

This is my axios post request from the front end:

addClient = async e => {

let newUser = {
                businessname: businessname.toLowerCase(),
                firstName: firstName.toLowerCase(),
                lastName: lastName.toLowerCase(),
                email,
                username,
                password,
                phoneNumber,
                customerStatus: customerStatus.value,
                userType,
                Gooduntil
            };
            const accessString = localStorage.getItem("JWT");
            await Axios.post("/auth/signup", newUser, {
                headers: { Authorization: `JWT ${accessString}` }
            })
                .then(res => {
                    console.log(res);
                    return this.setState({
                        loadingAxiosReq: false
                    });
                })
                .catch(err => {
                    return console.log(err);
                });
}

Here is my post route:

router.post("/signup", verifyToken, (req, res) => {
    console.log(req.headers);

    const {
        businessname,
        username,
        firstName,
        lastName,
        phoneNumber,
        email,
        password,
        customerStatus,
        userType,
        Gooduntil
    } = req.body;

    if (password.length < 8) {
        throw "Password must be at least 8 characters";
    } else {
        User.findOne({
            where: {
                email
            }
        }).then(user => {
            if (user) {
                return res.send("Email already exists!");
            } else {
                const encryptedPassword = bcrypt.hashSync(password, salt);

                let newUser = {
                    businessname,
                    username,
                    firstName,
                    lastName,
                    phoneNumber,
                    email,
                    password: encryptedPassword,
                    customerStatus,
                    userType,
                    Gooduntil
                };
                User.create(newUser)
                    .then(() => {
                        // newUser.isAdmin = true
                        delete newUser.password;
                        res.send(newUser);
                    })
                    .catch(function(err) {
                        console.log(err);
                        res.json(err);
                    });
            }
        });
    }
});

And this is my middleware:

const jwt = require("jsonwebtoken");

module.exports = function(req, res, next) {
    const token = req.header("JWT");
    if (!token) return res.status(401).send("Access Denied!");

    try {
        const verified = jwt.verify(token, process.env.JWT_SECRET);
        req.user = verified;
        return next();
    } catch (err) {
        res.status(400).send("Invalid Token!");
    }
};

So, how can I properly make my axios request? Thanks in advance.

1

1 Answers

1
votes

From this line I can see you are checking for a header named JWT.

const token = req.header("JWT");

But in axios you are sending the Authorization header:

{ headers: { Authorization: `JWT ${accessString}` }

You need to send the JWT header. Also alternatively, if you want to check the Authorization header just check for that:

const token = req.headers['authorization'];

Also, Just send the <token>, if you send JWT <token> then you would need to split the header and check only the <token> part.