当前位置:网站首页>Using JSON webtoken (JWT) to generate token in nodejs
Using JSON webtoken (JWT) to generate token in nodejs
2020-11-06 22:11:00 【The front end of the attack】
Ⅰ- one - jsonwebtoken brief introduction
One Why token
-
http No state
-
session Can't cross servers
-
cors Cross domain later cookie Can't use
In separate projects , Each request session Will change , The front end calls the back end api Interface , Therefore use cors = require('cors')
To solve the cross domain problem , And cross domain for cookie Come on , It's two different websites , therefore session Will keep changing .
In computer authentication, it's a token ( temporary ) It means , In lexical analysis, the meaning of mark . In general, what we call token Most of them are used for authentication token
We need to know every time who the current request is , But I don't want him to submit his user name and password every time , At this point, we need to have something that is equivalent to the user's name and password to identify the user's identity , namely —token
Two What is? token
token It is composed of three segments of encrypted string to .
Separate, for example xxxxxxxxxxxxxxxxxxxxx.yyyyyyyyyyyyyyyyyyyyyyyy.zzzzzzzzzzzzz
-
The first paragraph : head , visa : Security information verification , Your password , Do irreversible encryption *
-
The second paragraph : The information you want to save : basa64 Intercept the content after encryption ,
-
The third paragraph : Additional information : Irreversible encryption
The first and third paragraphs are irreversible encryption Hash hash , The second paragraph base64 Reversible encryption
This string is sent from the back end to the front end , After landing again , Generate a token To the front end
Ⅱ - Ii. - jsonwebtoken Use
Download and use
npm i jsonwebtoken
||
yarn add jsonwebtoken
stay nodejs Directly import
// 0. Import
const jwt = require('jsonwebtoken')
Two jsonwebtoken Method
1 Generate token:
jwt.sign( The information you want to save , password , Parameters )
-
Saved information
-
password : encrypted password , When encrypting, mix in information to use , You need this password when decrypting
-
Parameters : It's an object , {}
expiresIn: Expiration time , The unit is in seconds (‘1d’)*
2 decode token:
jwt.verify( What you're trying to parse token, password , Callback function )
-
token: It has to be a designated token
-
password : It must be the password at the time of encryption
-
Callback function : Receive results
const express = require('express')
const jwt = require('jsonwebtoken')
const cors = require('cors')
const router = express.Router()
const app = express()
app.use(cors())
// Prepare one token Verification middleware
app.use(function (req, res, next) {
// req.url Indicates the current address
const {
url, headers: {
authorization: token } } = req
// const url = req.url
// const { authorization: token } = req.headers
// const token = req.headers.authorization
// It doesn't need to be verified Request address
if (url === '/login' || url === '/banner') return next()
// Coming here means you need to token verification
if (!token) return res.send({
message: ' Please bring token request ', code: 0 })
jwt.verify(token, 'Josiah', (err, data) => {
if (err && err.message === 'invalid token') return res.send({
message: ' Invalid token', code: 0 })
if (err && err.message === 'jwt expired') return res.send({
message: 'token invalid ', code: 0 })
next()
})
})
router.get('/login', (req, res) => {
// Successful login by default
const userInfo = {
username: 'XXX',
age: 18
}
// Generate a token Back to the front end
const token = jwt.sign(userInfo, 'Josiah, {
expiresIn: 60 })
res.send({
message: ' Login successful ', code: 1, token })
})
// Second test
router.get('/cartInfo', (req, res) => {
res.send({
message: ' Successfully obtained shopping cart data ', code: 1 })
})
router.get('/pay', (req, res) => {
res.send({
message: ' Successful payment ', code: 1 })
})
// First test
// router.get('/cartInfo', (req, res) => {
// You want cart data
// Then you have to log in later
// verification token Is it right
// req, It's the information of this request
// req.headers This is the request header of this time
// const token = req.headers.authorization
// // 1. Is there any
// if (!token) return res.send({ message: ' The request requires token', code: 0 })
// // 2. Isn't it
// jwt.verify(token, 'guoxiang', (err, data) => {
// if (err && err.message === 'invalid token') return res.send({ message: ' Invalid token', code: 0 })
// if (err && err.message === 'jwt expired') return res.send({ message: 'token invalid ', code: 0 })
// res.send({ message: ' Successfully obtained shopping cart data ', code: 1 })
// })
// })
router.get('/banner', (req, res) => {
// You need carousel information
// No login verification required
res.send({
message: ' Rotation chart data acquisition successful ', code: 1, list: [ {
}, {
} ] })
})
app.use(router)
app.listen(8080, () => console.log('running at 8080'))
3、 ... and Test use
token The generation and decoding of
// 0. Import
const jwt = require('jsonwebtoken')
// Prepare a message
const userInfo = {
_id: '2131245655',
username: ' Little star ',
age: 18,
gender: ' male '
}
// 1. Generate a token
const res = jwt.sign(userInfo, 'key', {
expiresIn: 20 })
console.log(res)
//res The content will be generated
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
// eyJfaWQiOiIyMTMxMjQ1NjU1IiwidXNlcm5hbWUiOiLpg63nv5QiLCJhZ2UiOjE4LCJnZW5kZXIiOiLnlLciLCJpYXQiOjE1OTkxOTk2MDYsImV4cCI6MTU5OTE5OTYxNn0.
// Cg-PxkAzTnCUF9xja1O9gcOmRzaRsw4TlFM2nCZenAw
// 2. decode
jwt.verify(res, 'key', (err, data) => {
console.log(' for the first time 1.5s')
if (err) return console.log(err)
console.log(data)
})
Ⅲ - 3 - Third party plug-ins express-jwt
- It's a express The framework and jwt Combined third party middleware
- effect : verification token
- Using this plug-in requires and sonwebtoken Use it together
Be careful :
- If you want to use it express-jwt You have to have a global error middleware
- natural token Back to the front end , Need to be written Bearer token
The plug-ins used in the following cases :
express、jsonwebtoken、express-jwt、cors
app.js
const express = require('express')
const jwt = require('jsonwebtoken')
const expressJWT = require('express-jwt')
const cors = require('cors')
const router = expryicisess.Router()
const app = express()
app.use(cors());// Solving cross domain problems
// app.use() It's inside expressJWT().unless()
// register token Verification middleware
app.use(expressJWT({
// Parse the password , It needs to be the same as when encrypting
secret: 'Josiah',
// encryption : SHA256 The encryption method is in express-jwt It's called HS256
algorithms: ['HS256']
}).unless({
// No validation required token Path identifier for
path: ['/login', '/banner']
}))
router.get('/login', (req, res) => {
// Successful login by default
const userInfo = {
username: ' Guo Xiang ',
age: 18
}
// Generate a token Back to the front end
const token = 'Bearer ' + jwt.sign(userInfo, 'Josiah', {
expiresIn: 60 })
res.send({
message: ' Login successful ', code: 1, token })
})
app.use(router)
// Error handling middleware
app.use((err, req, res, next) => {
res.send({
err })
})
app.listen(8080, () => console.log('running at 8080'))
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button> Sign in </button>
<script>
// If you are doing background management system , Generally stored in sessionStorage
// window.sessionStorage.setItem('abc', '100')
// Front end carrying token We store it in Request header Inside
// authorization: token
const xhr = new XMLHttpRequest()
const token = window.localStorage.getItem('token')
xhr.open('GET', 'http://localhost:8080/cartInfo')
xhr.onload = function () {
const res = JSON.parse(xhr.responseText)
console.log(res)
}
xhr.setRequestHeader('authorization', token)
xhr.send()
</script>
</body>
</html>
0 - 0 - Knowledge point :
One It's generating token When
You need to add Bearer
There's a space after that
const token = 'Bearer ' + jwt.sign(userInfo, 'guoxiang', { expiresIn: 60 })
Second, we are analyzing token When
- Parse the password , It needs to be the same as when encrypting
- encryption : SHA256 The encryption method is in express-jwt It's called HS256
// app.use() It's inside expressJWT().unless()
// register token Verification middleware
app.use(expressJWT({
// Parse the password , It needs to be the same as when encrypting
secret: 'guoxiang',
// encryption : SHA256 The encryption method is in express-jwt It's called HS256
algorithms: ['HS256']
}).unless({
// No validation required token Path identifier for
path: ['/login', '/banner']
}))
3、 ... and When the front end gets
- If you are doing background management system , Generally stored in sessionStorage
- Front end carrying token We store it in Request header Inside , In general use authorization
xhr.setRequestHeader('authorization', token)
版权声明
本文为[The front end of the attack]所创,转载请带上原文链接,感谢
边栏推荐
- 2020-08-17: how to solve data skew in detail?
- The role of theme music in games
- ado.net and asp.net The relationship between
- Open source a set of minimalist front and rear end separation project scaffold
- Event monitoring problem
- Detailed software engineering -- the necessary graphs in each stage
- 应用层软件开发教父教你如何重构,资深程序员必备专业技能
- How does cglib implement multiple agents?
- How much disk space does a new empty file take?
- Why is quicksort so fast?
猜你喜欢
2020-08-17:详细说下数据倾斜怎么解决?
轻量型 GPU 应用首选 京东智联云推出 NVIDIA vGPU 实例
Stm32f030f4p6 compatible with smart micro mm32f031f4p6
Exclusive interview of guests at | 2020 PostgreSQL Asia Conference: Wang Tao
An article taught you to download cool dog music using Python web crawler
How much disk space does a file of 1 byte actually occupy
20个XR项目路演,近20个资本机构出席!诚邀您参加2020 Qualcomm XR生态合作伙伴大会
Detect certificate expiration script
Metersphere developer's Manual
[learning] interface test case writing and testing concerns
随机推荐
image operating system windows cannot be used on this platform
Mongo user rights login instruction
#JVM 类加载机制
2020-08-29:进程线程的区别,除了包含关系之外的一些区别,底层详细信息?
2020-08-29: process thread differences, in addition to the inclusion relationship, the underlying details?
The method of local search port number occupation in Windows system
Jenkins installation and deployment process
JVM memory allocation - xms128m - xmx512m - XX: permsize = 128M - XX: maxpermsize = 512M
Why is quicksort so fast?
打工人好物——磨炼钢铁意志就要这样高效的电脑
小熊派开发板实践:智慧路灯沙箱实验之真实设备接入
【涂鸦物联网足迹】涂鸦云平台全景介绍
2020-08-19:TCP是通过什么机制保障可靠性的?
A good thing for working people -- to temper the will of iron and steel requires such an efficient computer
Reserved battery interface, built-in charge and discharge circuit and electricity meter, quickly help easily handle hand-held applications
Python 100 cases
How much disk space does a file of 1 byte actually occupy
Stm32f030c6t6 compatible to replace mm32spin05pf
Novice guidance and event management system in game development
STM32F030F4P6兼容灵动微MM32F031F4P6