当前位置:网站首页>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]所创,转载请带上原文链接,感谢
边栏推荐
- 汽车维修app开发的好处与功能
- DC-1 target
- With this artifact, quickly say goodbye to spam messages
- 小程序商城系统插件代码该如何写?怎么用代码检查添加插件是否成功?
- Google browser realizes video playback acceleration function
- Code generator plug-in and creator preform file analysis
- All the way, I was forced to talk about C code debugging skills and remote debugging
- Stm32f030k6t6 compatible replacement smart mm32f031k6t6
- 2020-08-19:TCP是通过什么机制保障可靠性的?
- 如何才能快速正确的部署甘特图
猜你喜欢
What the hell is fastthreadlocal? The existence of ThreadLocal!!
Python basic data type -- tuple analysis
The Interpreter pattern of behavior pattern
How to start the hidden preferences in coda 2 on the terminal?
Summary of front-end interview questions (C, s, s) that front-end engineers need to understand (2)
Road to simple HTML + JS to achieve the most simple game Tetris
The native API of the future trend of the front end: web components
[byte jumps, autumn recruitment Posts open] ohayoo! Don't leave after school, I want to ask you to play games!!!
2020年新规,微信封号怎么快速解除?
Understanding formatting principles
随机推荐
2020-08-15: under what circumstances should data tasks be optimized?
Zero basis to build a web search engine of its own
What is the tensor in tensorflow?
移动端像素适配方案
Common syntax corresponding table of mongodb and SQL
消防器材RFID固定资产管理系统
How much disk space does a file of 1 byte actually occupy
August 14, 2020: what are the execution engines for data tasks?
What the hell is fastthreadlocal? The existence of ThreadLocal!!
Visual rolling [contrast beauty]
Detect certificate expiration script
The use of Xunwei imx6 development board device tree kernel menuconfig
Understanding formatting principles
#JVM 类加载机制
Event monitoring problem
Elasticsearch database | elasticsearch-7.5.0 application construction
Exclusive interview of guests at | 2020 PostgreSQL Asia Conference: Wang Tao
Js字符串-String字符串对象方法
2020-08-24:什么是小文件?很多小文件会有什么问题?很多小文件怎么解决?(大数据)
The essence of transaction and the principle of deadlock