当前位置:网站首页>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]所创,转载请带上原文链接,感谢
边栏推荐
- C and C / C + + mixed programming series 5 - GC collaboration of memory management
- win7 APPCRASH(解决方法)(转)
- Characteristics of magnetic memory chip STT-MRAM
- Markdown tricks
- August 24, 2020: what are small documents? What's wrong with a lot of small files? How to solve many small files? (big data)
- 20个XR项目路演,近20个资本机构出席!诚邀您参加2020 Qualcomm XR生态合作伙伴大会
- The Interpreter pattern of behavior pattern
- 2020-08-19: what mechanism does TCP ensure reliability?
- What the hell is fastthreadlocal? The existence of ThreadLocal!!
- Design of NAND flash interface control
猜你喜欢
August 30, 2020: naked write algorithm: the nearest common ancestor of two nodes in a binary tree.
Reserved battery interface, built-in charge and discharge circuit and electricity meter, quickly help easily handle hand-held applications
2020-09-04: do you understand the function call convention?
Js字符串-String字符串对象方法
Stm32f030k6t6 compatible replacement smart mm32f031k6t6
Message queue - Analysis
image operating system windows cannot be used on this platform
心理咨询app开发所具备的优点与功能
Empty test suite appears in JUnit test
2020-08-19:TCP是通过什么机制保障可靠性的?
随机推荐
Python basic variable type -- list analysis
Git remote library rollback specified version
Nodejs中使用jsonwebtoken(JWT)生成token的场景使用
How to prepare for the system design interview
Js数组-数组的用法全在这里(数组方法的重构、数组的遍历、数组的去重,数组的判断与转换)
Common mathematical basic formulas of recursive and backtracking algorithms
Using an example to understand the underlying processing mechanism of JS function
list转换map(根据key来拆分list,相同key的value为一个list)
A concise tutorial for Nacos, ribbon and feign
细数软件工程----各阶段必不可少的那些图
磁存储芯片STT-MRAM的特点
Utility class functions (continuous update)
NAND FLASH的接口控制设计
An article taught you to download cool dog music using Python web crawler
Stm32f030f4p6 compatible with smart micro mm32f031f4p6
#JVM 类加载机制
Code generator plug-in and creator preform file analysis
Introduction to the development of small game cloud
2020-09-04: do you understand the function call convention?
1万辆!理想汽车召回全部缺陷车:已发生事故97起,亏损将扩大