<分区>
我想在我的 express Node 应用程序中使用 express-jwt,但我找不到任何演示登录部分的示例。
有什么帮助吗?
<分区>
我想在我的 express Node 应用程序中使用 express-jwt,但我找不到任何演示登录部分的示例。
有什么帮助吗?
最佳答案
我建议您尝试了解 JWT 的原理以及它们如何在服务器和客户端之间传递以及如何根据 secret 匹配服务器端 - 这里是 doc
有效负载可以是任意用户数据——即:只是用户名或 ID
基本上,您需要一个在成功验证时生成 token 的服务(当用户使用正确的凭据登录时,即:usr & pwd)并创建一个带有 token 的附加 header ,以便在对服务器的进一步请求中使用。
对于 jwt-express您显然需要安装软件包(与 jsonwebtoken 相同),例如:
npm install jwt-express --save
然后像这样初始化它:
var jwt = require('jwt-express');
app.use(jwt.init('secret'));
来自文档:
The jwt.init() function returns a middleware function for Express so it must be called inside app.use(). It will automatically read in the JWT from either the cookie or the Authorization header (configured by you) and add a JWT object to the Request object (req). It will also add the jwt() method to the Response object (res) to create / store JWTs. jwt.init() must be called before any other jwt method.
这些是你的选择:
其余的逻辑由您编写代码,但我的示例应该让您清楚地了解如何在您的应用程序中管理 jwt。
这是我如何通过 jsonwebtoken 实现 jwt 的示例:
// INFO: Function to create headers, add token, to be used in HTTP requests
createAuthenticationHeaders() {
this.loadToken(); // INFO: Get token so it can be attached to headers
// INFO: Headers configuration options
this.options = new RequestOptions({
headers: new Headers({
'Content-Type': 'application/json', // INFO: Format set to JSON
'authorization': this.authToken // INFO: Attach token
})
});
}
// INFO: Function to get token from client local storage
loadToken() {
this.authToken = localStorage.getItem('token');; // Get token and assign to variable to be used elsewhere
}
和一些存储用户状态的功能,即:
// INFO: Function to store user's data in client local storage
storeUserData(token, user) {
localStorage.setItem('token', token); // INFO: Set token in local storage
localStorage.setItem('user', JSON.stringify(user)); // INFO: Set user in local
storage as string
this.authToken = token; // INFO: Assign token to be used elsewhere
this.user = user; // INFO: Set user to be used elsewhere
}
以及销毁本地存储中 token 的注销功能,即:
// INFO: Function for logging out
logout() {
this.authToken = null; // INFO: Set token to null
this.user = null; // INFO: Set user to null
localStorage.clear(); // INFO: Clear local storage
}
如果你使用 npm 的 jsonwebtoken ,你可以在生成 token 时设置 token 的ttl:
const token = jwt.sign({ id: idDB }, "secret", { expiresIn: '24h' });
或者您想要的任何 ttl,字符串“secret”指的是与服务器匹配的 secret 。
关于node.js - express-jwt 的任何完整示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46364199/