当前位置:网站首页>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
边栏推荐
- leetcode 509. Fibonacci Number(斐波那契数字)
- Unity C# 函数笔记
- ESXI挂载移动(机械)硬盘详细教程
- 剑指offer-高质量的代码
- [opencv] morphological filtering (2): open operation, morphological gradient, top hat, black hat
- Etcd database source code analysis -- starting from the start function of raftnode
- 品牌·咨询标准化
- 中英文说明书丨ProSci LAG-3 重组蛋白
- POI export to excel: set font, color, row height adaptation, column width adaptation, lock cells, merge cells
- 一条慢SQL拖死整个系统
猜你喜欢
2018年江苏省职业院校技能大赛高职组“信息安全管理与评估”赛项任务书
POI export to excel: set font, color, row height adaptation, column width adaptation, lock cells, merge cells
2018年江苏省职业院校技能大赛高职组“信息安全管理与评估”赛项任务书第二阶段答案
Stack and queue-p79-9
Config分布式配置中心
How can I check the DOI number of a foreign document?
unity3d学习笔记
品牌电商如何逆势增长?在这里预见未来!
BindingException 异常(报错)处理
Abnova 免疫组化服务解决方案
随机推荐
SVN version management in use replacement release and connection reset
POI export to excel: set font, color, row height adaptation, column width adaptation, lock cells, merge cells
Problems and precautions about using data pumps (expdp, impdp) to export and import large capacity tables in Oracle migration
2022 Android interview essential knowledge points, a comprehensive summary
反射(二)
一条慢SQL拖死整个系统
What are the classic database questions in the interview?
MATLAB小技巧(29)多项式拟合 plotfit
MYSQL----导入导出&视图&索引&执行计划
mobx 知识点集合案例(快速入门)
联合索引ABC的几种索引利用情况
JVM in-depth
ViewModelProvider.of 过时方法解决
工具类:对象转map 驼峰转下划线 下划线转驼峰
C interview encryption program: input plaintext by keyboard, convert it into ciphertext through encryption program and output it to the screen.
7天零基础能考证HCIA吗?华为认证系统学习路线分享
Performance comparison between Ceres solver and g2o
SolidWorks GB Library (steel profile library, including aluminum profile, aluminum tube and other structures) installation and use tutorial (generating aluminum profile as an example)
Abnova 免疫组化服务解决方案
impdp的transform参数的测试