且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

nodejs + express + jwt token鉴权登录用例

更新时间:2022-05-20 09:17:11

导语

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