当前位置:网站首页>Authenticated cookies, sessions, JWT
Authenticated cookies, sessions, JWT
2022-06-22 11:49:00 【Wang Xiaomiao】
authentication : Determine whether a user has access to resources on the server .
The user center page can only be accessed after the user logs in ;
An interface requires token Ability to visit ;
http It's stateless :
In the early web Just provide information to the visitors , There is no need to record the status . Browsers and servers cannot rely on HTTP Protocol to identify the context of the request . ( The server cannot tell whether the request sent by the browser has been requested before . )
Basic realization idea of authentication :
The identity information is stored on the server .( Apply for consumption card , The customer came and reported the card number , Query on the system )
The identity information is saved in the client .( Apply for consumption card , When the customer comes, he stamps the card directly )
1.cookie Basic introduction :
cookie It is the server that persists the data ( preservation ) Store to client ( browser ) A technique .
cookie Is a string in the form of a key value pair
You can view the of a website through a browser cookie
1.1cookie The role of :
The local store . Temporary storage of a small amount of data ;
Because it will be carried automatically when requesting from the browser cookie, So it can be used for permission verification .


1.2cookie Authentication solution :
User login successful , server setting cookie
The user will automatically bring the next request cookie, Server resolution cookie, Determine whether to log in
User exits , Server delete cookie 
const express = require('express')
const app = express()
app.use(express.static('public'))
app.use(express.urlencoded())
app.post('/login',(req,res)=>{
// res.setHeader('Access-Control-Allow-Origin', '*')
// How to receive application/json The data of ?
console.log(' The data received is ', req.body)
const {name, password} = req.body
if( name === 'admin' && password === '123456') {
// Set individual cookie
res.setHeader('set-cookie', 'islogin=yes');
res.json({msg:' Login successful '})
} else {
res.json({msg:' Login failed '})
}
})
app.get('/testcookie',(req,res) => {
res.send('/testcookie')
})
app.get('/quit', (req, res) => {
res.send(' Delete cookie')
})
app.listen(3000, ()=>{
console.log(3000);
})1.2 Acceptance effect :
Click login... On the page , In developer tools , Observe
Check whether this response has set-cookie head .
testing application Next cookie Is there any value in .
Local settings cookie After success , When the client browser sends a request to the server , Will be automatically carried in the request cookie, It is kept in req.headers.cookie in .
1.3 Get on the server side cookie:
Install first npm install cookie-parser
// Install first npm install cookie-parser
// Use
var cookieParser = require('cookie-parser');
app.use(cookieParser());
// call , Modify the back-end code
app.get('/testcookie',(req,res) => {
console.log(' Requested to carry cookie yes ', req.cookies)
res.json({msg: ' test cookie',data: req.cookies})
})1.4 Delete on the server side cookie:
//express The framework provides a deletion method . Delete from the server :
app.get('/quit', (req, res) => {
res.clearCookie('name');
res.clearCookie('isLogin');
res.redirect('/login.html');
});2.cookie Basic introduction :
2.1session How Authentication works :
session Literally , It's conversation . It works by :
When the user logs in successfully , The server side will generate a sessionid, And pass set-cookie The generated sessionid Return to the client
Client received sessionid Will save it in cookie in , When the client accesses the server again, it will bring this sessionid
When the server receives the request from the client again , Will first check whether there is sessionid, Create a new one if it doesn't exist sessionid repeat 1,2 The process of , If it exists, traverse the server session file , Find something with this sessionid The corresponding file , The key value in the file is sessionid, The value is some information of the current user

adopt cookie What is returned to the browser is session Number ; The real data is on the server side .
2.2session Solution
stay express Within the framework of , We can install express-session Package to achieve session The function of .
//1. introduce session package
const session = require('express-session');
const app = express();
//2. Configuration item
let conf = {
secret: '123456', // Encrypted string . Use this string to encrypt session data , Customize
resave: false, // Force save session Even if it doesn't change
saveUninitialized: false // Force uninitialized session Storage . When I create a new one session And not
// When setting attributes or values , It's in an uninitialized state .
};
//3. Use express-session
app.use(session(conf));Set on the server side session(req.session. Property name = Property value )
app.post('/login', (req, res) => {
// Login successful
// Save data to session
req.session.isLogin = true;
req.session.name = req.body.username;
res.end()
}
Server side access session(req.session. Property name )
The server deletes session(req.session.destroy() )
app.get('/quit', (req, res) => {
req.session.destroy();
}3.cookie and session Comparison
cookie principle :
Leave information from the server side to the client browser
Set the response header :set-cookie;The browser carries this information every time it accesses the server ( Automatic carrying cookie Is a feature of the browser );
session principle :
The server side will provide for each user ( browser ) Keep one each session( file ). When the server saves session after , Will cookie The form tells the browser , Yours session Which number is it . It is the session No. is returned to the browser , Save the real data on the server .
The next time you visit the server , The browser will bring its own session No. to visit , Server according to session You can find the corresponding session 了 .
cookie: The advantage is to save server space , Disadvantages are unsafe . Do not save sensitive information .
session: The advantage is safety , Disadvantages require server space ( Server restart , Then the data is lost ), Is one of the most common solutions .
4.JWT(json web token) Basic introduction
token It means “ token ”, Is a string generated by the server , As an identity of the client to make the request .
JWT The principle is , After server authentication , Generate a JSON object , Send back to user , It looks like this .
{
" full name ": " Zhang San ",
" role ": " Administrators ",
" Due time ": "2022 year 7 month 11 Japan 0 spot 0 branch "
}in the future , When the user communicates with the server , Send this back JSON object . The server only relies on this object to identify the user . Of course , To prevent users from tampering with data , When the server generates this object , I will encrypt it for him , It is a long string that we see .
The problem to be solved is : Cross domain authentication solution 
Basic steps :
Use third-party modules jsonwebtoken establish token character string , Download and install in the project
npm i jsonwebtokenLoad module const jwt = require('jsonwebtoken');
After the user logs in successfully , call jwt.sign() Method creation token, It has the following 4 Parameters :
Parameters 1: Required , Objects form ; Hope that in token Data stored in
Parameters 2: Required , String form ; The key to encryption ; Subsequent verification token When , You also need to use
Parameters 3: Optional , Objects form ; Configuration item , For example, it can be configured token The validity of the
Parameters 4: Optional , Function form ; Generate token After the callback
Generated token front , Splicing must
BearerThis string .const express = require('express') const multer = require('multer') const cors = require('cors') const app = express(); app.use(cors({origin:true,credentials:true})) const jwt = require('jsonwebtoken'); app.use(express.urlencoded()) app.post('/login',(req,res)=>{ console.log(' The data received is ', req.body) const {name, password} = req.body if(password === '123456') { // Call to generate token Methods const tokenStr = jwt.sign({name: name }, 'heima61', { expiresIn: 5 }); const token = 'Bearer ' + tokenStr res.json({msg:' Login successful ', token}) } else { res.json({msg:' Login failed '}) } }) app.get('/test',(req,res) => { res.json({msg: ' test tokenOk'}) }) app.listen(3000, ()=>{ console.log(3000); })Browser side : Save the data returned from the backend token( Save in localStorage )
$('#btn_login').click(function(){ $.ajax({ type:'post', url:'http://localhost:3000/login', data:{name:$('#username').val(),password:$('#password').val()}, success(res){ console.log(res); + localStorage.setItem('token', res.token) } }) })Browser side : Carry it manually when sending a request token( Must be placed in Authorization in )
$('#btn_testToken').click(function(){ $.ajax({ type:'get', url:'http://localhost:3000/test', headers: { + Authorization: localStorage.getItem('token'), }, success(res){ console.log(res); } }) })Server side : Realization token authentication ( Choose to use express-jwt The third-party module performs identity authentication . From the module name, you can see , This module is specially designed to cooperate with express The use of . )
const expressJwt = require('express-jwt'); // app.use(jwt().unless()); // jwt() For parsing token, And will token Data stored in Assign a value to req.user // unless() Agree that an interface does not require identity authentication app.use(expressJwt({ secret: 'heima61', // Generate token At the time of the The key , Must be unified algorithms: ['HS256'] // Required , encryption algorithm , There is no need to know }).unless({ path: ['/login'] // Except for interfaces , Everything else needs Certification }));After the above code is completed , When an interface request arrives at the server , It will automatically validate the... In the request header Authorization Field , And it will automatically complete :
If there is no problem
take token Stored in the data Assign a value to req.user
next().
If there are questions , Throws an error next( error message ).
Supplement middleware technology - Unified error handling ( At the end of all routes , Add error handling middleware , To prompt the token A mistake in . )
app.use((err, req, res, next) => {
if (err.name === 'UnauthorizedError') {
// res.status(401).send('invalid token...');
res.status(401).send({ status: 1, message: ' Authentication failed !' });
}
});边栏推荐
- Arm load storage instruction
- Realization of simple particle effect in canvas
- 牛客练习赛94D题解
- Solution to 54e of Niuke challenge
- Bytestream case of IO
- 初识ElastricSearch
- Vector data of Zunyi city's benchmark land price in 2022 (WGS84)
- IO之Reader案例
- R语言使用自定义函数编写深度学习Parametric ReLU激活函数、并可视化Parametric ReLU激活函数
- In a word, several common methods of uploading Trojan horse
猜你喜欢

1.11 haas506 2.0 development tutorial driver RTC (only versions above 2.2 are supported)

Niuke challenge 53c

APM set pitch four rotor control mode

《梦华录》成吸金王:广告主投500万排不上队,腾讯视频赢麻了?

把蔚来告上法庭,奥迪急什么?

How much memory does a TCP connection occupy?

How many of the eight classic MySQL errors did you encounter?

electron添加SQLite數據庫

从原型链到继承,图解来龙去脉,推荐收藏

Wechat applet project example - image processing gadget (self-made low configuration version of Meitu XiuXiu)
随机推荐
Puzzle (019) plane forward problem
Niuke challenge 54F problem solution & Li Chaoshu's learning notes
CF751 C. Optimal Insertion
How much memory does a TCP connection occupy?
TCP connection establishment process (in-depth understanding of the source code and three handshakes)
牛客挑战赛54F题解 & 李超树学习笔记
electron添加SQLite數據庫
IO之ByteArrayStream案例
KNN classification of MATLAB (with source code) is used to realize pixel classification (set the proportion of training set by yourself) and print test accuracy
开源代码存在安全隐患:一个项目平均有49个漏洞
arc128 C 凸包优化后缀和?
Haas506 2.0 development tutorial - Advanced Component Library -modem Info (only supports versions above 2.2)
R language uses GLM function to build Poisson log linear regression model, processes three-dimensional contingency table data to build saturation model, and uses summary function to obtain model summa
Arm load storage instruction
R语言dplyr包mutate函数将dataframe中的两个数值变量相除创建新的数据列(Create a new variable)
General graph maximum matching (with flower tree) template
奋斗吧,程序员——第四十章 一面风情深有韵,半笺娇恨寄幽怀
牛客挑战赛55E题解
Security risks exist in open source code: an average of 49 vulnerabilities exist in a project
R language uses user-defined functions to write step activation functions for deep learning and visualize step activation functions
