如何在express中生成和设置`JWT_SECRET`和`JWT_EXPIRATION_TIME`

问题描述 投票:0回答:5

当我运行我的服务器时,我遇到了以下错误。

Error: Config validation error: "JWT_SECRET" is required. "JWT_EXPIRATION_TIME" is required

因此我必须设置JWT密钥等等。

我想知道如何设置

JWT_SECRET
。但我不知道如何生成和设置它们。

我设置了

.env
文件,我必须在其中配置一些变量。

我的

.env
文件如下。

.env

JWT_SECRET=
JWT_EXPIRATION_TIME=

如果有人知道生成

SECRET
的好方法,请告诉我。

谢谢

javascript node.js express secret-key
5个回答
7
投票

正如@Arya 和@JaromandaX 所提到的,您必须在

JWT_SECRET
之后输入类似这样的
JWT_SECRET=yourfavoritecolor
JWT_EXPIRATION_TIME=3600
的内容。您可以在代码中使用
process.env.JWT_SECRET
process.env.JWT_EXPIRATION_TIME
来调用它们。

查看这篇关于 JWT 的文章 - 实现 JWT 的正确方法


6
投票

您可以通过运行以下命令在控制台中生成令牌:

node -e "console.log(require('crypto').randomBytes(32).toString('hex'));"

然后将生成的令牌添加到您的

.env
文件中


3
投票

非常简单,您只需将其添加到您的

.env
文件中

JWT_SECRET=  any text or number you want to add here to create jwt Token
JWT_EXPIRATION_TIME= you have to specify time limit like you want thattoken expire in 24 hours you have to add  60 * 60 * 24 or  86400 // 24 hours

并且没有其他方法可以生成

secrert


2
投票

其他用户已经回答了如何设置 JWT_SECRET 的问题,我将添加如何生成它。 @slebetman 给出了使用密码生成器生成字符串的好建议(它们既单独存在,又作为大多数密码管理器的一部分)。为此,我通常使用以下命令,只需在终端中输入该命令并将其复制到 .env 文件即可:

openssl rand -base64 172 | tr -d '\ n'

其中

172
是生成的字符串中的字符数(选择您想要的)。

希望对您有帮助:)


0
投票

用于在express中生成

JWT_SECRET
JWT_EXPIRATION_TIME
首先,您需要在系统中安装 jwtwebtoken
npm i jsonwebtoken
之后,您必须使用此导入 jwtwebtoken
var jwt = require('jsonwebtoken');

定义您的密钥和过期时间

const JWT_SECRET = 'your-secret-key';
const JWT_EXPIRATION_TIME = '1h'; // Set your desired expiration time, e.g., '1h' for 1 hour

使用密钥对 JWT 令牌进行签名并设置过期时间

var token = jwt.sign(data, JWT_SECRET, { expiresIn: JWT_EXPIRATION_TIME });

您可以设置定义您的密钥和过期时间 在

.env
本地文件中,然后访问它

有关更多详细信息,您可以查看https://www.npmjs.com/package/jsonwebtoken 提供我正在工作的代码示例,请仔细阅读以获取更多理解

const User = require("../models/User");
const router = express.Router();
const { body, validationResult } = require("express-validator");
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

// Define your secret key and expiration time
const JWT_SECRET = 'your-secret-key';
const JWT_EXPIRATION_TIME = '1h';  // Set your desired expiration time, e.g., '1h' for 1 hour

// Create a user using: Post "/api/auth/createUser", No login required
router.post(
  "/createUser",
  [
    body("name").isLength({ min: 3 }),
    body("email").isEmail(),
    body("password").isLength({ min: 5 }),
  ],
  async (req, res) => {
    // If there are errors then print errors
    const result = validationResult(req);
    if (!result.isEmpty()) {
      res.status(400).json({ errors: result.array() });
    }

    // Check whether the user with the same details exists already
    try {
      let user = await User.findOne({ email: req.body.email });
      if (user) {
        return res
          .status(400)
          .json({ error: "Sorry, a user with this email already exists" });
      }

      const salt = await bcrypt.genSaltSync(10);
      const secPass = await bcrypt.hash(req.body.password, salt);

      // Create a new user
      user = await User.create({
        name: req.body.name,
        password: secPass,
        email: req.body.email,
      });

      const data = {
        user: {
          id: user.id
        }
      };

      // Sign the JWT token using the secret key and set the expiration time
      var token = jwt.sign(data, JWT_SECRET, { expiresIn: JWT_EXPIRATION_TIME });

      res.json({ token });
    } catch (error) {
      console.error(error.message);
      res.status(500).send("Some error occurred");
    }
  }
);

module.exports = router;
© www.soinside.com 2019 - 2024. All rights reserved.