用户首先登录。一旦用户通过登录过程,或者我们说一旦用户通过身份验证,您就签署一个 jwt 令牌并将其发送给用户。这是 node.js sn-p
async postLogin(req, res, next) {
// parse the req.body, get the email,password
// check if the email exist, if exists check the passord
// now you are sure credentials are true, create the jwt.
const token = jwt.sign({ _id: this._id, email: this.email }, "this-is-secret", {
expiresIn: "1h",
res
.status(200)
.header("x-auth-token", token)
.json({ token, userId: existingUser._id.toString() });
});
}
现在客户端会将其保存到 localStorage。 (为简单起见,我使用 localStorage)。在客户端,用户发送 post 请求登录并获取我上面发送的内容。它将获取令牌并保存它。因为是异步请求,所以会是这样。这是一个小反应代码来演示:
.then(resData => {
localStorage.setItem('token', resData.token);
localStorage.setItem('userId', resData.userId);
关于令牌的一件事,浏览器不会自动发送它,所以客户端会手动将它附加到请求中。
fetch(url, {
method: "post",
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token')
}
})
一旦你的服务器收到请求,你检查传入的令牌,如果它是一个有效的令牌,你将授权用户访问某些路由或服务。所以用户将被授权。
身份验证是识别用户并验证他们声称的身份的过程。验证身份的最常见和最明显的因素之一是密码。如果用户名与密码凭据匹配,则表示身份有效,系统授予用户访问权限,因此我们说用户已通过身份验证