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.pngverifyToken
verifyToken.png带 authorization
authorization.png无 authorization
without_authorization.png不对称
authorization_unsymmetric.png未过期
expiresIn_1.png过期
expiresIn_2.pngJWT
JWTJWT Signature Verify
JWT Signature VerifyJWT 会引起 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
网友评论