我正在使用 passportJs 对我的应用程序上的用户进行身份验证,我可以创建用户,为他们创建凭据,并且他们可以毫无问题地登录。对于受保护的路线,我使用的是 passport-jwt 策略,所有路线都可以正常工作。但是,我一直在尝试对创建这些用户的路由使用相同的护照策略,但无论我做什么,我总是得到未经授权的响应 401。在前端,我使用 react 和 axios。这是我的护照代码:
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);
}
})
);
这是创建用户的路线:
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);
});
}
});
}
}
);
此 JWTstrategy 适用于创建用户的所有获取路由,但此路由除外。
这是我从前端的请求:
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));
}
这是我得到的错误:错误:请求失败,状态码为 401
有谁知道为什么会这样?我可以使它工作的唯一方法是从注册路线中删除护照-JWT 策略,但这并不安全。请帮忙!