有一个饼干!
这是通过安全 cookie 完成的。
signUp(email: string, password: string, passwordConfirm: string, name: string): Observable<User> {
const url = `${this.BASE_URL}/users/signup`;
return this.http.post<User>(url, {email, password, passwordConfirm, name}, {
withCredentials: true, // this part is very important
});
}
//Node js
const createAndSendToken = (user, statusCode, req,res) => {
const token = signToken(user._id, user.name);
const cookieOptions = {
expires: new Date(
Date.now() + process.env.JWT_COOKIE_EXPIRES_IN * 24 * 60 * 60 * 1000
),
httpOnly: true
}
// if(process.env.NODE_ENV === 'production') cookieOptions.secure = true;
if(req.secure || req.headers('x-forwarded-proto') === 'https') cookieOptions.secure = true; //this part is for heroku, it's important to have secure option set to true inside cookieOptions
res.cookie('jwt', token, cookieOptions);
user.password = undefined;
res.status(statusCode).json({
status: 'success',
token,
data: {
user
}
})
}
在此之后,您只为一个来源设置 cors 选项,并且凭据需要为真。
连接必须通过 https 协议。如果一切正常,cookie 将自动存储。打开控制台,然后在 Storage 下打开 Application 你有 Cookies 并检查是否有 cookie。在每个请求中,您都可以访问 Rest Api 中的 cookie
exports.isLoggedIn = async (req, res, next) => {
if (req.cookies.jwt) {
try {
// 1) Verification token
const decoded = await promisify(jwt.verify)(req.cookies.jwt, process.env.JWT_SECRET)
// 2) Check if user still exists
const currentUser = await User.findById(decoded.id);
if(!currentUser) {
return next();
}
// 4) Check if user changed password after the token was issued
if(currentUser.changedPasswordAfter(decoded.iat)) {
return next()
}
//THERE IS A LOGGED IN USER
req.user = currentUser;
return next();
} catch(err) {
return next();
}
}
next();
}
在每次重新加载 Angular 应用程序时,我们都会调用此函数。