I am using passportJs to authenticate users on my app, I can create users, create them credentials, and they can login with no issues. For the protected routes, I'm using passport-jwt strategy, and all routes work just fine. However, I have been trying to use the same passport strategy for the route that creates those users, but no matter what I do I always get the unauthorized response 401. On the front end I use react and axios. Here is my passport code:
const opts = {
jwtFromRequest: ExtractJWT.fromAuthHeaderWithScheme("JWT"),
secretOrKey: process.env.JWT_SECRET
};
passport.use(
"jwtToPostUser",
new JWTstrategy(opts, (jwt_payload, done) => {
try {
User.findOne({
where: {
email: jwt_payload.email
}
}).then(user => {
if (user) {
console.log("user found in db in passport");
done(null, user);
} else {
console.log("user not found in db");
done(null, false);
}
});
} catch (err) {
done(err);
}
})
);
Here is the route to create users:
router.post(
"/signup",
passport.authenticate("jwtToPostUser", { session: false }),
(req, res, next) => {
console.log(req.body);
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) {
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);
});
}
});
}
}
);
This JWTstrategy works for all the get routes, except for this one, that creates the user.
Here is my 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",
{
headers: {
Authorization: `JWT ${accessString}`
}
},
newUser
)
.then(res => {
console.log(res);
this.setState({
loadingAxiosReq: false
});
})
.catch(err => console.log(err));
}
This it the error I'm getting: Error: Request failed with status code 401
Does anybody know why is this happening? The only way I can make it work is by removing the passport-JWT strategy from the signup route, but that's not secure. please help!