当前位置:网站首页>JWT-JSON WEB TOKEN
JWT-JSON WEB TOKEN
2022-07-06 06:14:00 【Snow peak expensive】
List of articles
One 、JWT What is it? ?
Two 、JWT The composition of
- Header: Record the type of token , Signed algorithm name .{“alg”:“HS256”,“type”:“JWT”}
- Payload: Record user information .{“username”:“GXF”,“id”:“1”}
- Signature: prevent Token Be tampered with , Improve safety . according to Header and Payload A string calculated .
3、 ... and 、Token form
token=BASE64(Header).BASE64(Payload).BASE64(Signature)
Four 、Signature The composition of
Signature By Header Inside alg Calculated by the specified algorithm .
Signature= Specified algorithm (BASE64(Header).BASE64(Payload), secret key )
5、 ... and 、 Use
- Plus dependence
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.10.7</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.10.7</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.10.7</version>
<scope>runtime</scope>
</dependency>
- Add configuration
jwt:
secret: 123456 # secret key
# The period of validity , Unit second , Default 2 Zhou
expire-time-in-second: 1209600
- Machining tools
import com.google.common.collect.Maps;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@RequiredArgsConstructor
@SuppressWarnings("WeakerAccess")
@Component
public class JwtOperator {
/** * Secret key * - Default aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrsssttt */
@Value("${secret:aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrsssttt}")
private String secret;
/** * The period of validity , Unit second * - Default 2 Zhou */
@Value("${expire-time-in-second:1209600}")
private Long expirationTimeInSecond;
/** * from token In order to get claim * * @param token token * @return claim */
public Claims getClaimsFromToken(String token) {
try {
return Jwts.parser()
.setSigningKey(this.secret.getBytes())
.parseClaimsJws(token)
.getBody();
} catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | IllegalArgumentException e) {
log.error("token Parse error ", e);
throw new IllegalArgumentException("Token invalided.");
}
}
/** * obtain token The expiration time of * * @param token token * @return Expiration time */
public Date getExpirationDateFromToken(String token) {
return getClaimsFromToken(token)
.getExpiration();
}
/** * Judge token Is it overdue * * @param token token * @return Expired return true, Not expired return false */
private Boolean isTokenExpired(String token) {
Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}
/** * Calculation token The expiration time of * * @return Expiration time */
public Date getExpirationTime() {
return new Date(System.currentTimeMillis() + this.expirationTimeInSecond * 1000);
}
/** * Generate... For the specified user token * * @param claims User information * @return token */
public String generateToken(Map<String, Object> claims) {
Date createdTime = new Date();
Date expirationTime = this.getExpirationTime();
byte[] keyBytes = secret.getBytes();
SecretKey key = Keys.hmacShaKeyFor(keyBytes);
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(createdTime)
.setExpiration(expirationTime)
// You can also use your favorite algorithm
// The supported algorithms are detailed in :https://github.com/jwtk/jjwt#features
.signWith(key, SignatureAlgorithm.HS256)
.compact();
}
/** * Judge token Is it illegal * * @param token token * @return Not expired return true, Otherwise return to false */
public Boolean validateToken(String token) {
return !isTokenExpired(token);
}
// public static void main(String[] args) {
// // 1. initialization
// JwtOperator jwtOperator = new JwtOperator();
// jwtOperator.expirationTimeInSecond = 1209600L;
// jwtOperator.secret = "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrsssttt";
//
// // 2. Set user information
// HashMap<String, Object> objectObjectHashMap = Maps.newHashMap();
// objectObjectHashMap.put("id", "1");
//
// // test 1: Generate token
// String token = jwtOperator.generateToken(objectObjectHashMap);
// // Something similar to this string will be generated : eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJpYXQiOjE1NjU1ODk4MTcsImV4cCI6MTU2Njc5OTQxN30.27_QgdtTg4SUgxidW6ALHFsZPgMtjCQ4ZYTRmZroKCQ
// System.out.println(token);
//
// // Change me to the one generated above token!!!
// String someToken = "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJpYXQiOjE1NjU1OTQ1NjIsImV4cCI6MTU2NjgwNDE2Mn0.PAvWPcQAZnSlYKNbZr4O1l9aA4LPphuq0OG2QIs7O5E\n";
// // test 2: If you can token Legal and not expired , return true
// Boolean validateToken = jwtOperator.validateToken(someToken);
// System.out.println(validateToken);
//
// // test 3: Get user information
// Claims claims = jwtOperator.getClaimsFromToken(someToken);
// System.out.println(claims);
//
// // Change me to the one you generated token The first paragraph of ( With . As boundary )
// String encodedHeader = "eyJhbGciOiJIUzI1NiJ9";
// // test 4: Decrypt Header
// byte[] header = Base64.decodeBase64(encodedHeader.getBytes());
// System.out.println(new String(header));
//
// // Change me to the one you generated token The second paragraph of ( With . As boundary )
// String encodedPayload = "eyJpZCI6IjEiLCJpYXQiOjE1NjU1ODk1NDEsImV4cCI6MTU2Njc5OTE0MX0";
// // test 5: Decrypt Payload
// byte[] payload = Base64.decodeBase64(encodedPayload.getBytes());
// System.out.println(new String(payload));
//
// // test 6: This is a falsified token, Therefore, an exception will be reported , explain JWT Is safe
// jwtOperator.validateToken("eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJpYXQiOjE1NjU1ODk3MzIsImV4cCI6MTU2Njc5OTMzMn0.nDv25ex7XuTlmXgNzGX46LqMZItVFyNHQpmL9UQf-aUxxx");
// }
}
边栏推荐
- (中)苹果有开源,但又怎样呢?
- [C language] string left rotation
- LeetCode 732. 我的日程安排表 III
- ICLR 2022 spotlight | analog transformer: time series anomaly detection method based on correlation difference
- Testing and debugging of multithreaded applications
- Isam2 operation process
- 对数据安全的思考(转载)
- JDBC Requset 对应内容及功能介绍
- 【LeetCode】Day96-第一个唯一字符&赎金信&字母异位词
- GTSAM中李群的運用
猜你喜欢
LeetCode 731. 我的日程安排表 II
[C language] string left rotation
Understanding of processes and threads
[API interface tool] Introduction to postman interface
【Postman】测试(Tests)脚本编写和断言详解
单元测试的意义
【eolink】PC客户端安装
黑猫带你学eMMC协议第10篇:eMMC读写操作详解(read & write)
Request forwarding and redirection
IPv6 comprehensive experiment
随机推荐
Title 1093: character reverse order
【C语言】qsort函数
selenium源码通读·9 |DesiredCapabilities类分析
Function of activation function
win10无法操作(删除、剪切)文件
Cognitive introspection
D - How Many Answers Are Wrong
曼哈顿距离与曼哈顿矩形-打印回字型矩阵
数据库-当前读与快照读
SQLMAP使用教程(三)实战技巧二
二维码的前世今生 与 六大测试点梳理
全链路压测:构建三大模型
LeetCode 731. 我的日程安排表 II
Cannot create PoolableConnectionFactory (Could not create connection to database server. 错误
[postman] collections configuration running process
Overview of three core areas of Mathematics: algebra
ContentType的作用
Nodejs realizes the third-party login of Weibo
[postman] collections - run the imported data file of the configuration
P问题、NP问题、NPC问题、NP-hard问题详解