【问题标题】:how to handle custom token with express.js如何使用 express.js 处理自定义令牌
【发布时间】:2020-05-10 05:19:48
【问题描述】:

我有一个node express APP。 我知道我们可以使用“jsonwebtoken”和“express-jwt”。至。验证并生成令牌。但我的问题是,如果我的令牌不是由 jsonwebtoken 生成的怎么办。如何应用令牌保护我的 API?

【问题讨论】:

  • 您能否提供一个如何生成令牌的示例代码。
  • 我的令牌由第三方 API 生成,这意味着只能由该 API 验证
  • 不过,以下答案可以为您工作,但您不需要步骤 1 和 2。在步骤 4 中,在 try-catch 中,您可以调用 3rd 方 API 并工作相应地。

标签: node.js express node-modules


【解决方案1】:

基本上,方法是。

  1. 创建一个函数以根据需要生成自定义令牌。
const sign = (data, secret) => {
  //your logic goes here
}
  1. 创建一个验证令牌的函数。
const verify = (token, secret) => {
   // returns error or decoded data
}
  1. 登录成功后想创建令牌时调用它
const login = (req, res) => {
  // login code goes here say its success
  const token = sign({id: _id}, process.env.SECRET_KEY)
  res.json({token: token})
}

  1. 验证在受保护路由中收到的令牌。为其创建一个中间件函数。
function verifyToken(req, res, next) {

  //token from the request header
  const authHeader = req.headers['authorization'] // -> or key of your choice
  const token = authHeader && authHeader.split(' ')[1]
  if (token == null) return res.sendStatus(401) // if there isn't any token

  try{
      const data = verify(token, process.env.SECRET_KEY) => {
      if (err) return res.status(403)
      req.user_id = data.id // this one will let you read data in the calling service function
      next() // pass the execution off to whatever request the client intended
    }
  } catch (err) {
     res.send(err)
  }
}

  1. 从令牌中读取数据
const getUserInfo = (req, res) => {
    const id = req['user_id'];
    // now you can get the user data using this id that we used while signing the token.
}

现在我知道令牌是由第 3 方提供的,只能由他们验证。

所以在这种情况下,

function verifyToken(req, res, next) {

  //token from the request header
  const authHeader = req.headers['authorization'] // -> or key of your choice
  const token = authHeader && authHeader.split(' ')[1]
  if (token == null) return res.sendStatus(401) // if there isn't any token

  try{
      // make the verify call to the 3rd party api by sending the token 
      // received in the request
      const data = ApiCall();

      /* set that data into the header, if you may want to use it later or 
       * do whatever you want to do.
       */
      req.resp_data = data;
      next(); // sent control to next function.

  } catch (err) {
     res.send(err)
  }
}

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    • 2021-10-06
    • 2018-07-17
    • 2022-01-27
    • 1970-01-01
    • 2020-08-29
    相关资源
    最近更新 更多