当前位置:网站首页>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
边栏推荐
猜你喜欢

原理:WebMvcConfigurer 与 WebMvcConfigurationSupport避坑指南

不忘初心,能偷懒就偷懒:C#操作Word文件

RT thread migration to s5p4418 (IV): thread synchronization

与MQTT的初定情缘
![[Hot100]回文子串 与 最长回文子串](/img/a5/10dec640f02023c4d55cb42e6309fb.png)
[Hot100]回文子串 与 最长回文子串

Pycharm shortcut key

RT thread migration to s5p4418 (I): scheduler

银河麒麟初体验

1.5 - logical operation

Steps for formulating class or file templates in idea
随机推荐
Initial love with mqtt
Introduction to programming ape (11) -- structure
Fastapi learning Day1
How does the CPU recognize the code?
C语言:练习题三
Xshell传输文件
Browser downloads files as attachments
Bat 使用细节2
图解八股,真的太顶了
RT thread Kernel Implementation (III): implementation of idle threads and blocking delay
gazebo/set_ model_ State topic driving UAV model through posture
Record one time of Tencent Test Development Engineer's automation interface test practice experience
How to convert XML to JSON
SOC_ AHB_ SD_ IF
Fastapi learning Day2
【模糊神经网络】基于模糊神经网络的移动机器人路径规划
The solution of memcpy memory overlap
【我的创作纪念日】一周年随笔
1.7 - CPU performance indicators
Records of problems solved (continuously updated)