当前位置:网站首页>Basic introduction of JWT
Basic introduction of JWT
2022-07-07 06:50:00 【Children haha】
Preface
JWT It is mainly used for user login authentication , The traditional method is session authentication .
http It's a stateless agreement , When a user authenticates the user with the account name and password to the system , The next request needs another user authentication . Because we can't go through http The protocol knows which user sent the request , So if you want to know which user sent the request , Then you need to save a copy of user information on the server ( Save to session), Then return after successful authentication cookie Value passed to browser , Then the user can bring it with him at the next request cookie value , The server can identify which user sent the request , Is it certified , Whether the login expires .
session The shortcomings of certification are obvious , because session Is saved in the server , So if you deploy applications distributed , There will be session Problems that can't be shared , It's hard to expand .
JWT Introduction to
JWT:Json Web Token It defines a compact 、 The self-contained way , Used as a JSON Objects transmit information securely between parties . This information can be verified and trusted , Because it's digitally signed .
technological process :
- Users use accounts 、 Password login application , The login request is sent to Authentication Server.
- Authentication Server User authentication , Then create JWT String returned to client .
- When a client requests an interface , On the request headband JWT.
- Application Server verification JWT Legitimacy , If it is legal, continue to call the application interface and return the result
User information is saved on the client , The key is to generate JWT And analysis JWT.
JWT Data structure of
JWT Generally, it is such a string , It's divided into three parts , With "." separate .
xxxxx.yyyyy.zzzzz
Header: The first part is the head part , describe JWT Metadata Json object
{
"alg": "HS256",
"typ": "JWT"
}
alg Property indicates the algorithm used for signature , The default is HMAC SHA256( Written as HS256),typ Property indicates the type of token ,JWT Token is uniformly written as JWT. Last , Use Base64 URL The algorithm will JSON Object to string save .
Payload: The second part is Payload, Also a Json object , In addition to containing the data to be transmitted , There are seven default fields to choose from .
Namely ,iss: The issuer 、exp: Due time 、sub: The theme 、aud: user 、nbf: Not available until 、iat: Release time 、jti:JWT ID Used to identify the JWT.
If custom fields , It can be defined as :
{
// Default fields
"sub":" The theme 123",
// Custom field
"name":"java Technology enthusiasts ",
"isAdmin":"true",
"loginTime":"2021-12-05 12:00:03"
}
JSON Objects also use Base64 URL Algorithm converted to string save .
Signature: The third part is signature . This is how it was generated , First, you need to specify a secret, The secret Save only in the server , Make sure that other users don't know . And then use Header The specified algorithm pair Header and Payload Calculate , Then you get a signature hash .
JWT The advantages of :
- json The generality of the format , therefore JWT Can support cross language , such as Java、JavaScript、PHP、Node wait .
- You can use Payload Store some non sensitive information .
- Easy to transmit ,JWT Simple structure , Small byte footprint .
- There is no need to save session information on the server , Easy to apply extensions .
Use JWT
Import dependence
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
Create a tool class , Used to create jwt String and parsing jwt
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import java.util.Date;
/**
*
* @description JWT: token token Generate
*/
public class TokenUtil {
// token The period of validity
private static final long EXPIRATION = 86400L;//1day = 86400L
/**
*
* @description establish token Tool method
*/
public static String createToken(User user) {
JwtBuilder builder = Jwts.builder();
builder.setAudience(user.getUserCode()) // This user.getUserCode() It is the parameter I need later
.setIssuer("xxx")
.claim("userId", user.getId()) // userId It is the parameter I need later , This is set according to your own needs
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION * 1000));
String accessToken = builder.compact();
return accessToken;
}
/**
*
* @description verification token Back to the user code
*/
public static String validateToken(String token) {
Claims claims = Jwts.parserBuilder().build().parseClaimsJwt(token).getBody();
String userCode = claims.getAudience();
return userCode;
}
/**
*
* @description verification token Back to the user ID
*/
public static String getUserIdFromToken(String token) {
Claims claims = Jwts.parserBuilder().build().parseClaimsJwt(token).getBody();
String userId = claims.get("userId", String.class);
return userId;
}
}
Some minor modifications , I didn't use the third part here .
link :https://www.zhihu.com/question/485758060/answer/2257869896
边栏推荐
- Networkx绘图和常用库函数坐标绘图
- docker-compose启动redis集群
- POI export to excel: set font, color, row height adaptation, column width adaptation, lock cells, merge cells
- 使用net core优势/为什么使用
- Pinduoduo lost the lawsuit: "bargain for free" infringed the right to know but did not constitute fraud, and was sentenced to pay 400 yuan
- The latest trends of data asset management and data security at home and abroad
- MySQL installation
- Abnova 免疫组化服务解决方案
- Data of all class a scenic spots in China in 2022 (13604)
- C language interview to write a function to find the first occurrence of substring m in string n.
猜你喜欢
二十岁的我4面拿到字节跳动offer,至今不敢相信
Leetcode T1165: 日志分析
Doctoral application | Professor Hong Liang, Academy of natural sciences, Shanghai Jiaotong University, enrolls doctoral students in deep learning
The latest trends of data asset management and data security at home and abroad
Ha Qu projection dark horse posture, only half a year to break through the 1000 yuan projector market!
unity3d学习笔记
从零到一,教你搭建「CLIP 以文搜图」搜索服务(二):5 分钟实现原型
快速定量,Abbkine 蛋白质定量试剂盒BCA法来了!
反射(二)
Abnova 免疫组化服务解决方案
随机推荐
根据IP获取地市
ICML 2022 | explore the best architecture and training method of language model
怎样查找某个外文期刊的文献?
The difference between string constants and string objects when allocating memory
MOS tube parameters μ A method of Cox
JWT certification
impdp的transform参数的测试
Abnova 免疫组化服务解决方案
大促过后,销量与流量兼具,是否真的高枕无忧?
品牌电商如何逆势增长?在这里预见未来!
C language interview to write a function to find the first public string in two strings
from .onnxruntime_pybind11_state import * # noqa ddddocr运行报错
Programmers' daily | daily anecdotes
地质学类比较有名的外文期刊有哪些?
Common problems of caching in high concurrency scenarios
2018年江苏省职业院校技能大赛高职组“信息安全管理与评估”赛项任务书第一阶段答案
循环肿瘤细胞——Abnova 解决方案来啦
Bus消息总线
程序员的日常 | 每日趣闻
请问如何查一篇外文文献的DOI号?