第十四課時: 登錄/登出以及JWT認證

1.後端代碼概覽

// /login登錄接口
router.post('/login', function(req, res, next) {
  const {userName, password} = req.body
  if (userName) {
    const userInfo = password ? getPasswordByName(userName) : ''
    if (!userInfo || !pawwsord || userInfo.password !== password) {
      res.status(401).send({
        code: 401,
        mes: 'user name or password is wrong',
        data: {}
      })
    } else {
      res.send({
        code: 200,
        mes: 'success',
        data: {
          token: jwt.sign({ name: userName }, 'abcd', {
            expiresIn: 60
          })
        }
      })
    }
  } else {
    res.status(401).send({
      code: 401,
      mes: 'user name is empty',
      data: {}
    })
  }
})

// 接口攔截
const whiteListUrl = {
  get: {},
  post: {
    '/index/login'
  }
}

const hasOneOf = {str, arr} => {
  return arr.some(item => item.includes(str))
}

app.all('*', (req, res, next) => {
  let method = req.method.tolowerCase()
  let path = req.path
  if (whiteListUrl[method] && hasOneOf(path, whiteListUrl[methods])).next()
  else {
    const token = req.headers.authorization
    if (!token) res.status(401).send('there is no token, please login')
    else {
      jwt.verify(token, 'abcd', (error, decode) => {
        if (error) res.send({
          code: 401,
          mes: 'token error',
          data: {}
        }) else {
          req.userName = decode.name
          next()
        }
      })
    }
  }
})

2.登錄以及Token處理

(1)路由守衛判斷有沒有token,沒有的話進入login頁
(2)如果有的話,重新請求服務器獲取token,放入cookies,進入頁面
(3)login登錄成功後,返回token放入cookies
(4)每次請求的時候headers里加入token驗證

3.Token過期處理

後端代碼:

 token: jwt.sign({ name: userName }, 'abcd', {
        expiresIn: 60
      })

token設置爲60秒過期,每次請求

4.退出登錄

跳轉頁面,清除token

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章