当前位置:网站首页>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.zzzzzHeader: 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
边栏推荐
- 学习笔记|数据小白使用DataEase制作数据大屏
- A program lets you understand what static inner classes, local inner classes, and anonymous inner classes are
- MYSQL----导入导出&视图&索引&执行计划
- from .onnxruntime_pybind11_state import * # noqa ddddocr运行报错
- Stack and queue-p78-8 [2011 unified examination true question]
- Force deduction 62 different paths (the number of all paths from the upper left to the lower right of the matrix) (dynamic planning)
- Matlab / envi principal component analysis implementation and result analysis
- 项目实战 五 拟合直线 获得中线
- Navicat importing 15g data reports an error [2013 - lost connection to MySQL server during query] [1153: got a packet bigger]
- JWT certification
猜你喜欢

【NOI模拟赛】区域划分(结论,构造)

品牌·咨询标准化

ICML 2022 | explore the best architecture and training method of language model

MySQL installation

What books can greatly improve programming ideas and abilities?

Linear algebra (1)

学术报告系列(六) - Autonomous Driving on the journey to full autonomy

地质学类比较有名的外文期刊有哪些?

JWT certification

数据资产管理与数据安全国内外最新趋势
随机推荐
LVS+Keepalived(DR模式)学习笔记
当前发布的SKU(销售规格)信息中包含疑似与宝贝无关的字
品牌电商如何逆势增长?在这里预见未来!
[start from scratch] detailed process of deploying yolov5 in win10 system (CPU, no GPU)
MATLAB小技巧(29)多项式拟合 plotfit
Answer to the first stage of the assignment of "information security management and evaluation" of the higher vocational group of the 2018 Jiangsu Vocational College skills competition
【解决】Final app status- UNDEFINED, exitCode- 16
libcurl返回curlcode说明
程序员的日常 | 每日趣闻
Stack and queue-p79-9
DB2获取表信息异常:Caused by: com.ibm.db2.jcc.am.SqlException: [jcc][t4][1065][12306][4.25.13]
学习笔记|数据小白使用DataEase制作数据大屏
MySQL (x)
Stack and queue-p78-8 [2011 unified examination true question]
Pinduoduo lost the lawsuit: "bargain for free" infringed the right to know but did not constitute fraud, and was sentenced to pay 400 yuan
什么情况下考虑分库分表
RuntimeError: CUDA error: CUBLAS_STATUS_ALLOC_FAILED when calling `cublasCreate(handle)`问题解决
Basic DOS commands
Data of all class a scenic spots in China in 2022 (13604)
docker-compose启动redis集群