当前位置:网站首页>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
边栏推荐
猜你喜欢
MySQL优化:从十几秒优化到三百毫秒
Keil - the "trace HW not present" appears during download debugging
Judge whether H5 is in wechat environment or enterprise wechat environment at both ends
leetcode:98. 验证二叉搜索树
程序猿入门攻略(十一)——结构体
SOC项目AHB_SD_HOST控制器设计
Force buckle ------ replace blank space
Porting RT thread to s5p4418 (II): dynamic memory management
Relevant database questions.
1.8 - multi level storage
随机推荐
SOC_SD_CLK
1.8 - multi level storage
1.6 - CPU组成
力扣------替换空格
华泰炒股安全吗?我想网上开户。
Redis cache
【docsify基本使用】
Combat simulation system data
No module named 'pyqt5 QtMultimedia‘
1.5 - 逻辑运算
The most complete sentence in history
【每日一题】535. TinyURL 的加密与解密
ROS program compilation, like no compilation, refers to the execution of the old compiled executable program
C # - C # process and convert pixeldata of CT images with fo DICOM
MySQL中的InnoDB引擎
MySQL Optimization: from more than ten seconds to 300 milliseconds
Ffmplay is not generated during the compilation and installation of ffmpeg source code
1.4 - fixed and floating point numbers
c# - C#用fo-dicom对CT图像的PixelData进行处理和转换
原理:WebMvcConfigurer 与 WebMvcConfigurationSupport避坑指南