天天看點

nodejs + express + jwt token鑒權登入用例

導語

token鑒權登入的優勢:無狀态、可以跨域、可以防止csrf、性能好(每次請求不用去伺服器查詢相應的session),用戶端隻需要将token存入本地,每次通路服務端headers加上token即可

實作

  1. 安裝jwt

    npm install jsonwebtoken --save

  2. 生成一對RSA秘鑰(用來加密)用openssl來建立RSA256密鑰對
    進入項目内任意指定目錄:輸入openssl,如下
    ▶ openssl
    OpenSSL> genrsa -out jwt.pem 1024                        
    Generating RSA private key, 1024 bit long modulus
    ....++++++
    .......................++++++
    e is 65537 (0x10001)
        
    OpenSSL> rsa -in jwt.pem -pubout -out jwt_pub.pem
    writing RSA key
    OpenSSL> exit
    ls 
    jwt.pem       jwt_pub.pem            
  3. 登入接口上添加生成token方法
    login.createToken = (req, res, next) => {
        let result = req.body.result
        let cert = fs.readFileSync(path.resolve(__dirname, '../../lib/rsa/jwt.pem'))
        let token = jwt.sign({
            _id: result._id,
            name: result.name
        }, cert, {
            algorithm: 'RS256',
            expiresIn: '1h'
        })
        result.token = token
        return common.send(req, res, {status: 0, msg: '登入成功!', data: result})
    }           

    algorithm:加密算法方式

    expiresIn:Eg: 60, "2 days", "10h", "7d". A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default ("120" is equal to "120ms").(官方解釋)

  4. 在路由

    router.use

    方法内添加校驗token方法
    function checkToken(req, res, next) {
      let token = req.headers.token
      let cert = fs.readFileSync(path.resolve(__dirname, '../lib/rsa/jwt_pub.pem'))
      try {
        const decoded = jwt.verify(token, cert);
        next()
      } catch (e) {
        res.status(401)
        res.send(e)
      }
    }           

繼續閱讀