当前位置:网站首页>15 minutes learn to use JWT
15 minutes learn to use JWT
2022-06-30 06:55:00 【Hippo, TAS】
15 Learn to use in minutes JWT
brief introduction
What is? JWT?
JSON Web Token, By means of digital signature , With JSON The object is the carrier , Secure transmission of information between different service terminals .
JWT What's the usage? ?
JWT The most common scenario is authorization , Once the user logs in , Each subsequent request will contain JWT, Before each user request is processed by the system , You have to do it first JWT Security check , Process after passing .
JWT The composition of
JWT from 3 Part of it is made up of , use . Splicing
These are the three parts :
Header
{
'typ': 'JWT',
'alg': 'HS256'
}
token type jwt encryption algorithm HS256
Payload
{
'sub': '1234567890',
'name': 'john',
'admin': true
}
load Where valid information is stored A statement registered in the standard , Public statement , Private statement Conduct base64 Encryption gets the second part
Signature
var encodedString = base64UrlEncode(header) + '.' + base64UrlEncode(payload);
var signature = HMACSHA256(encodedString, 'secret');
Signature Add salt to encrypt to get the third part
rely on
pom.xml
<!-- Core dependence -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<!-- Use jwt, If it is jdk1.8 The above versions require these dependencies , Otherwise an error -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
encryption
Code example
@Test
public void testjwt() {
// establish jwt object
JwtBuilder jwtBuilder = Jwts.builder();
long time = 24*60*60*1000;
// First define the signature information
String signature = "admin";
//jwt Three parts , The creation is also divided into three parts
String jwtToken = jwtBuilder
//header
.setHeaderParam("typ", "JWT")
.setHeaderParam("alg","HS256")
//payload Loading
.claim("username", "tom")
.claim("role", "admin")
.setSubject("admin-test") // Add theme
.setExpiration(new Date(System.currentTimeMillis()+time)) // Plus effective time here is one day
.setId(UUID.randomUUID().toString())
//signature Define algorithms and variables
.signWith(SignatureAlgorithm.HS256, signature)
// The three parts should be put together
.compact();
// Output
System.out.println(jwtToken);
}
Get the output jwtToken
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRvbSIsInJvbGUiOiJhZG1pbiIsInN1YiI6ImFkbWluLXRlc3QiLCJleHAiOjE2MzUyNTkyMTMsImp0aSI6IjFhMWYxYmZiLTJjOTMtNDNlMy1hMDVlLWJmZGZhNzJlYmIyZCJ9.7d1ciA2FcmUTHSk-Kkq2bbV3Z5LLGaXBGFQBAlvUnsg
Decrypt
@Test
public void parse () {
String signature = "admin";
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRvbSIsInJvbGUiOiJhZG1pbiIsInN1YiI6ImFkbWluLXRlc3QiLCJleHAiOjE2MzUyNTkyMTMsImp0aSI6IjFhMWYxYmZiLTJjOTMtNDNlMy1hMDVlLWJmZGZhNzJlYmIyZCJ9.7d1ciA2FcmUTHSk-Kkq2bbV3Z5LLGaXBGFQBAlvUnsg";
JwtParser jwtParser = Jwts.parser();
Jws<Claims> claimsJws = jwtParser.setSigningKey(signature).parseClaimsJws(token);
Claims claims = claimsJws.getBody(); // What you get is a collection , Store all kinds of information in it
System.out.println(claims.get("username"));
System.out.println(claims.get("role"));
System.out.println(claims.getId());
System.out.println(claims.getSubject());
System.out.println(claims.getExpiration());
}
Get the output
tom
admin
1a1f1bfb-2c93-43e3-a05e-bfdfa72ebb2d
admin-test
Tue Oct 26 22:40:13 CST 2021
边栏推荐
- SOC_AHB_SD_IF
- leetcode:98. Validate binary search tree
- [mask RCNN] target detection and recognition based on mask RCNN
- The solution of memcpy memory overlap
- 【每日一题】535. TinyURL 的加密与解密
- 原理:WebMvcConfigurer 与 WebMvcConfigurationSupport避坑指南
- Joseph problem C language
- Practice summary of Prometheus project in amu Laboratory
- Fastapi learning Day2
- Record one time of Tencent Test Development Engineer's automation interface test practice experience
猜你喜欢

SOC项目AHB_SD_HOST控制器设计

ROS system problem: rosdep init

力扣------替换空格

Pay attention to this live broadcast and learn about the path to achieve the dual carbon goal of the energy industry

明天!“移动云杯”大赛空宣会开播!

银河麒麟初体验

gazebo/set_ model_ State topic driving UAV model through posture

Performance comparison of random network, scale-free network, small world network and NS small world matlab simulation

1.9 - Cache

【json-tutorial】第一章学习笔记
随机推荐
【转】存储器结构、cache、DMA架构分析
SOC_AHB_SD_IF
How does the CPU recognize the code?
【Hot100】15. 三数之和
1.9 - Cache
Initial love with mqtt
【docsify基本使用】
Principle: webmvcconfigurer and webmvcconfigurationsupport pit avoidance Guide
华泰炒股安全吗?我想网上开户。
0 basic job transfer software test, how to achieve a monthly salary of 9.5k+
Fastapi learning Day2
Record one time of Tencent Test Development Engineer's automation interface test practice experience
The solution of memcpy memory overlap
Introduction to programming ape (11) -- structure
[Hot100]10. 正则表达式匹配
gazebo/set_ model_ State topic driving UAV model through posture
[my creation anniversary] one year anniversary essay
Combat simulation system data
Records of problems solved (continuously updated)
Use of sscanf function