当前位置:网站首页>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]所创,转载请带上原文链接,感谢
边栏推荐
- window系统 本机查找端口号占用方法
- Flink's datasource Trilogy: direct API
- A concise tutorial for Nacos, ribbon and feign
- 2020-08-15: under what circumstances should data tasks be optimized?
- 应用层软件开发教父教你如何重构,资深程序员必备专业技能
- 迅为-iMX6ULL开发板上配置AP热点
- Markdown tricks
- List to map (split the list according to the key, and the value of the same key is a list)
- STM32F030F4P6兼容灵动微MM32F031F4P6
- What are the highlights of Huawei mate 40 series with HMS?
猜你喜欢
2020-08-19: what mechanism does TCP ensure reliability?
How to manage the authority of database account?
实验一
汽车维修app开发的好处与功能
[doodling the footprints of Internet of things] Introduction to Internet of things
What the hell is fastthreadlocal? The existence of ThreadLocal!!
Detailed software engineering -- the necessary graphs in each stage
Python basic data type -- tuple analysis
How much disk space does a file of 1 byte actually occupy
mongo 用户权限 登录指令
随机推荐
Unity performance optimization
Exclusive interview of guests at | 2020 PostgreSQL Asia Conference: Wang Tao
2020-09-04:函数调用约定了解么?
QT audio and video development 46 video transmission UDP version
How to make characters move
Js字符串-String字符串对象方法
Design of NAND flash interface control
上海巨微专用蓝牙广播芯片
DC-1 target
STM32F030K6T6兼容替换灵动MM32F031K6T6
How does cglib implement multiple agents?
Using iceberg on kubernetes to create a new generation of cloud original data Lake
Count the number of project code lines
移动端像素适配方案
Ora-02292: complete constraint violation (midbjdev2.sys_ C0020757) - subrecord found
Git remote library rollback specified version
Using an example to understand the underlying processing mechanism of JS function
JVM memory allocation - xms128m - xmx512m - XX: permsize = 128M - XX: maxpermsize = 512M
2020 database technology conference helps technology upgrade
Stm32f030c6t6 compatible to replace mm32spin05pf