简体   繁体   English

将 JWT 与 nodejs 和 express 一起使用

[英]Using JWT with nodejs and express

I'm trying to add JWT instead of express-session in the backend.我正在尝试在后端添加 JWT 而不是 express-session。 I can't figure out how to use it with nodejs + routes.我不知道如何将它与 nodejs + 路由一起使用。

I tried this, so i will be able to use it in every route:我试过了,所以我将能够在每条路线中使用它:

const jwt = 'jsonwebtoken'
app.use(jwt())

and I got that "jwt is not a function".我知道“jwt 不是函数”。

than I tried this:比我试过这个:

app.use(
  jwt.sign({}, 'secret')
);

and i got that "app.use() requires a middleware function" and instead of the {} I would like to enter the user when the frontend will pass one.我知道“app.use() 需要一个中间件函数”,而不是 {} 我想在前端通过一个时输入用户。

should I create jwtService file and import it to every route that use jwt?我应该创建 jwtService 文件并将其导入到每个使用 jwt 的路由中吗? or require jsonwebtoken in each route?或者在每条路线中都需要 jsonwebtoken?

确保你安装了这个包,你需要先导入/需要它。

const jwt =require('jsonwebtoken');

The way you can implement these libraries will always vary according to your project standard.您可以实现这些库的方式将始终根据您的项目标准而有所不同。

I will try to simplify a little bit here to make as much easier as I can.我将在这里尝试简化一点,以尽可能简化。

Let's suppose you have a /login route.假设您有一个/login路由。

const express = require('express')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')

const app = express();
app.use(bodyParser.json());
app.use(cookieParser());

app.post('/login', loginHandler); // YOUR route with JWT inside of login funciton.

app.listen(3000);

The second parameter of the app.post will be the function that has your JWT handlers in it, like: app.post的第二个参数是包含 JWT 处理程序的函数,例如:

const loginHandler = (req, res) => {
  // username and password
  const { username, password } = req.body

  // create new token
  const myJwtToken = jwt.sign({ username }, 
   jwtKey, {
    algorithm: 'HS256',
    expiresIn: XXSeconds // The expiredIn property can be human readable like '6 months', '1 week', etc.
  });

  console.log('My token is: ', myJwtToken);

  // set token and expiry date
  res.cookie('token', myJwtToken, { maxAge: XXSeconds * 1000 });
  res.end();
}

Useful links:有用的链接:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM