美文网首页
JSON Web Tokens ... | NodeJS 案例

JSON Web Tokens ... | NodeJS 案例

作者: 不知道的是 | 来源:发表于2018-06-30 05:46 被阅读0次

package.json

{
  "name": "08_JWT",
  "version": "1.0.0",
  "description": "JWT example",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.3",
    "jsonwebtoken": "^8.3.0"
  }
}

app.js

const express = require('express')

const jwt = require('jsonwebtoken')

const app = express()

app.get('/api', (req, res) => {
  res.json({
    message: 'Welcome to the API'
  })
})

app.post('/api/posts', VerifyToken, (req, res) => {
  jwt.verify(req.token, 'secretkey', (err, authData) => {
    if (err) {
      res.sendStatus(403)
    } else {
      res.json({
        message: 'Post created...',
        authData
      })
    }
  })
})

app.post('/api/login', (req, res) => {
  // Mock user
  const user = {
    id: 1,
    username: 'brad',
    email: 'brad@gmail.com'
  }

  jwt.sign({ user }, 'secretkey', { expiresIn: '30s' }, (err, token) => {
    res.json({
      token
    })
  })
})

// FORMAT OF TOKEN
// Authorization: Bearer <access_token>

// Verify Token
function VerifyToken(req, res, next) {
  // Get auth header value
  const bearerHeader = req.headers['authorization']
  // Check if bearer is undefined
  if (typeof bearerHeader !== 'undefined') {
    // Split at the space
    const bearer = bearerHeader.split(' ')
    // Get token from array
    const bearerToken = bearer[1]
    // Set the token
    req.token = bearerToken
    // Next middleware
    next()
  } else {
    // Forbidden
    res.sendStatus(403)
  }
}

app.listen(5000, () => {
  console.log('Server started on port 5000')
})

README.md

npm install express jsonwebtoken

npm install -g nodemon

/api

index.png

/api/posts

posts.png

/api/login

login.png

verifyToken

verifyToken.png

带 authorization

authorization.png

无 authorization

without_authorization.png

不对称

authorization_unsymmetric.png

未过期

expiresIn_1.png

过期

expiresIn_2.png

JWT

JWT

JWT Signature Verify

JWT Signature Verify

JWT 会引起 SIGNATURE 发生改变的因素 HEADER、PAYLOAD、密钥

引起 Signature 发生改变的因素 HEADER、PAYLOAD、密钥

JWT Header、Loader、Signature 详细说明

Header、Loader、Signature

仓库地址:
https://github.com/MonguDykrai/JWT-Demo

参考资料:
https://www.youtube.com/watch?v=7nafaH9SddU
https://tools.ietf.org/html/rfc7519
https://github.com/auth0/node-jsonwebtoken
https://blog.csdn.net/jack__frost/article/details/64964208

相关文章

网友评论

      本文标题:JSON Web Tokens ... | NodeJS 案例

      本文链接:https://www.haomeiwen.com/subject/pxozyftx.html