как обрабатывать пользовательский токен с помощью express. js - PullRequest
0 голосов
/ 08 мая 2020

У меня есть узел express APP. Я знаю, что мы можем использовать jsonwebtoken и express -jwt. к. проверить и сгенерировать токен. Но у меня вопрос: а что, если мой токен не сгенерирован jsonwebtoken. как я могу применить токен для защиты моего API?

1 Ответ

1 голос
/ 08 мая 2020

По сути, подход будет такой.

  1. Создайте функцию для генерации настраиваемого токена по своему усмотрению.
const sign = (data, secret) => {
  //your logic goes here
}
Создайте функцию, которая проверяет токен.
const verify = (token, secret) => {
   // returns error or decoded data
}
Вызывайте его всякий раз, когда хотите создать токен, скажем, после успешного входа в систему
const login = (req, res) => {
  // login code goes here say its success
  const token = sign({id: _id}, process.env.SECRET_KEY)
  res.json({token: token})
}

Проверить токен, полученный на защищенном маршруте. Создайте для него функцию промежуточного программного обеспечения.
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)
  }
}

Чтение данных с токена
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.
}

Теперь, когда я узнал, что токен предоставлен третьей стороной и может быть проверен только ими.

Итак, в в этом случае

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)
  }
}

Надеюсь, это помогло.

...