当前位置:网站首页>Just now, I popularized two unique skills of login to Xuemei
Just now, I popularized two unique skills of login to Xuemei
2020-11-06 01:17:00 【Yin Jihuan】
Today, I'd like to talk about a basic topic , It's how to log in ? Suitable for new friends .
Huashan Session Desperate learning
Session We call it Session control , Is a solution to maintain session state on the server side . Generally speaking, it is when the client accesses the server , The corresponding information will be stored in the server , Generate a Session ID Return to the client , The client will bring it next time it comes Session ID, So you can identify the visitor .
Bring... With you in the request Session ID The most common way is through Cookie To carry ,Cookie It is a mechanism for client to save user information , In the browser environment , The request will automatically come with Cookie Information , The server can also get Session ID.
When implementing the login logic in the back end , First get HttpSession object , And then through setAttribute() To set the login user information , Such as user ID. Verify if you have logged in getAttribute() To get the corresponding Session Information , If not , It proves that you have not logged in or the session has failed .
about Tomcat, Jetty For these containers ,Session Is a piece of memory space opened up in the server , The storage structure is Map.
Tomcat Of Session The implementation class is StandardSession.

Distributed Session Solution
If your application is a single node deployment , This scenario uses web Container implemented Session There's no problem with the mechanism . Once there's too much pressure , When multi node deployment is needed ,Session Distributed support is needed .
Look at the picture below , When two are deployed Tomcat When , adopt Nginx Load balancing , The first request was forwarded to Tomcat1, Session Information stored in Tomcat1 above . The second request was forwarded to Tomcat2 above , however Tomcat2 There's nothing on it Session Information , This is multi node Session There will be problems .

Session Copy
Tomcat Built in Session Copy function , It's your Session Is in Tomcat1 The result of ,Tomcat1 You will be Session Sync to Tomcat2, So when your request arrives Tomcat2 When , You'll be able to get your identity information .

This kind of scheme is often seen in other frameworks , such as Spring Cloud In the system Eureka Registry Center , It also uses replication to synchronize the registry information .
About Tomcat Session Please refer to the official document for copying the relevant configuration :https://tomcat.apache.org/tomcat-8.0-doc/cluster-howto.html
Sticky conversation
A sticky session is a request for the same user , Always forward to only one Tocmat On an instance of , So even if it's not done Session Copy , No problem . If a node fails, the access will fail .
The common way is to IP do Hash Forward ,IP Not very reliable , Because it will change . stay Nginx There is one of them. nginx-sticky-module This third-party module is used to add a stickiness Cookie, The viscosity cookie Always forward to the same server .
nginx-sticky-module Will be in Cookie Record a value in to identify which node the current request needs to be forwarded to , The first time you don't have it, you forward it first , Then write... Before the response is sent to the client Cookie. All subsequent requests will be in Cookie Find the corresponding logo , Then forward to the fixed node .

Session Centralized storage
Session Replication takes up server resources , Affect performance . There is a single point of failure risk in sticky conversations . Better distributed Session The way is centralized storage .
The so-called centralized storage is the unified storage of session information in a certain place , image Tomcat And so on. Web The server itself does not store session information , In this way, the back-end service is stateless , Easy to expand at any time .

As for the implementation scheme, there are many , You can do it yourself HttpSession Do the corresponding storage read logic , You can also use open source solutions . such as Spring Session It's a good open source solution , Easy to get started , Support multiple storage methods , such as Redis, Mysql etc. .
If you write by hand Spring Session Principles of interest , You can also refer to my previous course :http://cxytiandi.com/course/5
Shaolin Token Desperate learning
Token Authentication is one of the mainstream authentication methods ,Token The biggest advantage is no state , And you don't have to store session information . That is to say through Token You can know who the current user is visiting , There is no need to Web Get from the container's memory , There is no need to centrally manage session storage to get .
Token There are many ways to generate , You can define your own fixed format , For example, it contains users ID, User name and other information . You can also use the current mainstream JWT The way .
JWT(JSON Web Token) It is a kind of implementation based on JSON Open standards for .JWT The statement of identity is usually used to transfer authenticated user identity information between identity providers and service providers , In order to get resources from the resource server .
For example, when a user logs in , The basic idea is to provide the user name and password to the authentication server , The server verifies the validity of the information submitted by the user ; If the validation is successful , Will generate and return a Token, Then ask the user to bring this Token , The server can identify the identity of the request .
JWT It consists of three parts ,
- The first part is the head (Header);
- The second part is the message body (Payload);
- The third part is signature (Signature).
One JWT Generated Token The format is :
token = encodeBase64(header) + ‘.’ + encodeBase64(payload) + ‘.’ + encodeBase64(signature)
The information in the head usually consists of two parts , The type of token and the signature algorithm used , Consider the following code :
{ “alg”: “HS256”, “typ”: “JWT” }
The message body can carry some information needed by the application , Such as user ID, The code is as follows :
{ “id”: “1001”, “name”: “yinjihuan”}
A signature is used to determine whether a message has been tampered with on the path of delivery , So as to ensure the security of data , The format is as follows :
HMACSHA256( base64UrlEncode(header) + “.” + base64UrlEncode(payload), secret)
Through these three parts, we make up our JSON Web Token.
Please refer to Github:https://github.com/jwtk/jjwt
#

As shown in the figure above : Request arrival Tomcat after , You can call individual Token The service is carried out Token Generation , Can also be Token The generation logic of is encapsulated in a jar Bag to use . It should be noted that if you use the embedded method , Corresponding Token The encryption configuration should be consistent , Otherwise, the verification will fail .
Token It's a little bad that you can't take the initiative to let it fail , For example, we use Session Scene , User log out , Direct will Session The message can be deleted at the server , Even with the same Session Ask for information , The server can't find the corresponding information .
Token It's an encrypted string , It contains user information , encryption algorithm , Expiration time . If the expiration time is set to be long , That means you can use it before the expiration time .
If you want to realize the function of logging out , Since you can't be right about Token Its own expiration time is modified , Then you can use a blacklist mechanism to filter . Will log out of Token Store it , Use the place to match whether it's logged out , And then intercept it .
About author : Yin Jihuan , Simple technology enthusiasts ,《Spring Cloud Microservices - Full stack technology and case analysis 》, 《Spring Cloud Microservices introduction Actual combat and advanced 》 author , official account Ape world Originator .
I have compiled a complete set of learning materials , Those who are interested can search through wechat 「 Ape world 」, Reply key 「 Learning materials 」 Get what I've sorted out Spring Cloud,Spring Cloud Alibaba,Sharding-JDBC Sub database and sub table , Task scheduling framework XXL-JOB,MongoDB, Reptiles and other related information .

版权声明
本文为[Yin Jihuan]所创,转载请带上原文链接,感谢
边栏推荐
- Leetcode's ransom letter
- 【效能優化】納尼?記憶體又溢位了?!是時候總結一波了!!
- Flink的DataSource三部曲之二:内置connector
- WeihanLi.Npoi 1.11.0/1.12.0 Release Notes
- DRF JWT authentication module and self customization
- iptables基礎原理和使用簡介
- Sort the array in ascending order according to the frequency
- The practice of the architecture of Internet public opinion system
- Using consult to realize service discovery: instance ID customization
- 使用NLP和ML来提取和构造Web数据
猜你喜欢

做外包真的很难,身为外包的我也无奈叹息。

DRF JWT authentication module and self customization

如何将数据变成资产?吸引数据科学家

(1) ASP.NET Introduction to core3.1 Ocelot

Jmeter——ForEach Controller&Loop Controller

快快使用ModelArts,零基礎小白也能玩轉AI!

Didi elasticsearch cluster cross version upgrade and platform reconfiguration

制造和新的自动化技术是什么?

连肝三个通宵,JVM77道高频面试题详细分析,就这?

CCR炒币机器人:“比特币”数字货币的大佬,你不得不了解的知识
随机推荐
Chainlink将美国选举结果带入区块链 - Everipedia
事半功倍:在没有机柜的情况下实现自动化
PLC模拟量输入和数字量输入是什么
Synchronous configuration from git to consult with git 2consul
Listening to silent words: hand in hand teaching you sign language recognition with modelarts
Working principle of gradient descent algorithm in machine learning
Cocos Creator 原始碼解讀:引擎啟動與主迴圈
Basic principle and application of iptables
After brushing leetcode's linked list topic, I found a secret!
Tool class under JUC package, its name is locksupport! Did you make it?
DRF JWT authentication module and self customization
Query意图识别分析
Use of vuepress
分布式ID生成服务,真的有必要搞一个
DTU连接经常遇到的问题有哪些
The practice of the architecture of Internet public opinion system
【新閣教育】窮學上位機系列——搭建STEP7模擬環境
连肝三个通宵,JVM77道高频面试题详细分析,就这?
Elasticsearch 第六篇:聚合統計查詢
給萌新HTML5 入門指南(二)