node.js - express-jwt 的任何完整示例?

标签 node.js express express-jwt

<分区>

我想在我的 express Node 应用程序中使用 express-jwt,但我找不到任何演示登录部分的示例。

有什么帮助吗?

最佳答案

我建议您尝试了解 JWT 的原理以及它们如何在服务器和客户端之间传递以及如何根据 secret 匹配服务器端 - 这里是 doc

enter image description here

有效负载可以是任意用户数据——即:只是用户名或 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.

这些是你的选择:

  • cookie:(字符串)cookie 的名称(默认值:'jwt-express')
  • cookieOptions:(对象)存储 cookie 时使用的选项(默认值:{httpOnly: true})
  • cookies:( bool 值)如果为真,将使用 cookie,否则将使用授权 header (默认值:true)
  • refresh:( bool 值)指示是否应在每次请求时刷新和存储 JWT(默认值:true)
  • reqProperty:(字符串)要填充的请求的属性(默认值:'jwt')
  • revoke: (function) jwt.revoke() 将调用这个函数(默认:function(jwt) {})
  • signOptions:(对象)签署 JWT 时使用的选项(默认值:{})
  • stales:(数字)jwt 过时的毫秒数(默认值:900000(15 分钟))
  • 验证:(功能)附加验证。必须返回一个 bool 值(默认值:function(jwt) {return true})
  • verifyOptions:(对象)验证 JWT 时使用的选项(默认值:{})

其余的逻辑由您编写代码,但我的示例应该让您清楚地了解如何在您的应用程序中管理 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/

相关文章:

node.js - npm 生成的命令不调用 Node

node.js - 为什么当我运行 Express 服务器(React.js)时,我的浏览器显示空白页面?

javascript - 从数组中删除了错误的项目

ajax - node.js 表示 : How can I know if a request is an AJAX request?

JavaScript Express 返回空 JSON

node.js - JWT 签名 token 过期即使在代码中更改后浏览器应用程序中也不会更改

node.js - 使用 JWT token 机制实现从所有设备功能注销的方法有哪些?

node.js - Json 网络 token 不会过期

javascript - 什么是 html 模板中的自上而下/自下而上包含

javascript - 如何在 Express 中设置 json 响应的路由?