当前位置:网站首页>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]所创,转载请带上原文链接,感谢
边栏推荐
- Method of code refactoring -- Analysis of method refactoring
- Nonvolatile MRAM memory used in all levels of cache
- 2020-08-29:进程线程的区别,除了包含关系之外的一些区别,底层详细信息?
- 2020-08-20: the difference between go and python?
- STM32F030C6T6兼容替换MM32SPIN05PF
- Novice guidance and event management system in game development
- 2020-08-29: process thread differences, in addition to the inclusion relationship, the underlying details?
- 2020-08-18:介绍下MR过程?
- C calls SendMessage to refresh the taskbar icon (the icon does not disappear at the end of forcing)
- List to map (split the list according to the key, and the value of the same key is a list)
猜你喜欢
QT audio and video development 46 video transmission UDP version
1万辆!理想汽车召回全部缺陷车:已发生事故97起,亏损将扩大
Countdown | 2020 PostgreSQL Asia Conference - agenda arrangement of Chinese sub Forum
[forward] how to view UserData in Lua
Exclusive interview with Alibaba cloud database for 2020 PostgreSQL Asia Conference: Zeng Wenjing
To solve the problem that the data interface is not updated after WPF binding set
What the hell is fastthreadlocal? The existence of ThreadLocal!!
Detailed software engineering -- the necessary graphs in each stage
Windows 10 蓝牙管理页面'添加蓝牙或其他设备'选项点击无响应的解决方案
预留电池接口,内置充放电电路及电量计,迅为助力轻松搞定手持应用
随机推荐
上海巨微专用蓝牙广播芯片
How much disk space does a new empty file take?
Empty test suite appears in JUnit test
Count the number of project code lines
Git remote library rollback specified version
2020-08-17:详细说下数据倾斜怎么解决?
小熊派开发板实践:智慧路灯沙箱实验之真实设备接入
Event monitoring problem
Ora-02292: complete constraint violation (midbjdev2.sys_ C0020757) - subrecord found
2020-08-30:裸写算法:二叉树两个节点的最近公共祖先。
WebAPI接口设计:SwaggerUI文档 / 统一响应格式 / 统一异常处理 / 统一权限验证
Epu360: all the H5 templates you want are here, e-book, big turntable, red envelope rain, questionnaire survey
The 4th China BIM (digital construction) manager Summit Forum will be held in Hangzhou in 2020
Summary of front-end interview questions (C, s, s) that front-end engineers need to understand (2)
September 3, 2020: naked writing algorithm: loop matrix traversal.
细数软件工程----各阶段必不可少的那些图
Python basic variable type -- list analysis
August 24, 2020: what are small documents? What's wrong with a lot of small files? How to solve many small files? (big data)
迅为-iMX6ULL开发板上配置AP热点
List to map (split the list according to the key, and the value of the same key is a list)