express-jwt secret does not import process.env.JWT_SECRET



我试图使用process.env.JWT_SECRET的秘密,但它只是错误:

export const requireSignin = expressjwt({
secret: `${process.env.JWT_SECRET}`,
algorithms: ["HS256"],
userProperty: "auth",
});

这样我就没有错误了,但是然后我得到'UnauthorizedError: invalid signature'

export const requireSignin = expressjwt({
secret: process.env.JWT_SECRET,
algorithms: ["HS256"],
userProperty: "auth",
});

这样我得到"RangeError: express-jwt:secret是一个必需的选项">

export const requireSignin = () =>{
return expressjwt({
secret: process.env.JWT_SECRET,
algorithms: ["HS256"], 
userProperty: "auth",
}); 
}

这样就永远加载了。

export const requireSignin = expressjwt({
secret: '09f26e402586e2faa8da4c98a35f1b20d6b033c6097befa8be3486a829587fe2f90a832bd3ff9d42710a4da095a2ce285b009f0c3730cd9b8e1af3eb84df6611',
algorithms: ["HS256"],
userProperty: "auth",
});

这是唯一有效的方法(这是有问题的…)欢迎任何帮助,谢谢。

1 -安装dotenv

2 -在需要env变量的地方需要它:

require("dotenv/config");

你可以试试

npm install dotenv

并将其添加到server.js文件的顶部:

require('dotenv').config()

我建议使用以下包nmicro-router

配置JWT验证示例

import express  from 'express'
import { JWTAuth } from 'nmicro-jwt-auth' 
import {Router} from  'nmicro-router'
const JWT_VALIDATION_SECRET = process.env.JWT_SECRET 
const myRouter = new Router(express.Router())
myRouter.authHandler.setAdapter(new JWTAuth())  
const app = express()
app.use(express.json())
app.use(myRouter.router)
const myFn = (req, res) =>  res.send(`Hurray! It is working`) 
const options = { auth: true }
myRouter.post('/test', myFn, options)
const port = 8081
app.listen(port, () => console.log(`App listening in port ${port}`))

最新更新