当前位置:网站首页>JWT operation tool class sharing
JWT operation tool class sharing
2022-06-26 20:11:00 【A rookie is a great God】
Share your personal operation JWT Tool class of . be based on jjwt library , This is a Java The most popular in the circle JWT Operation Library .
TIPS
jjwtGitHub:GitHub - jwtk/jjwt: Java JWT: JSON Web Token for Java and Android- This tool class comes from personal open source certification 、 Authorization framework Light Security
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>Tool class :
@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 */ private 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.eyJpZCI6IjEiLCJpYXQiOjE1NjU1ODk4MTcsImV4cCI6MTU2Njc5OTQxN30.27_QgdtTg4SUgxidW6ALHFsZPgMtjCQ4ZYTRmZroKCQ"; // 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-aUx"); } }Write configuration
jwt: secret: Secret key # The period of validity , Unit second , Default 2 Zhou expire-time-in-second: 1209600Use :
@Autowired private JwtOperator jwtOperator; // ...
边栏推荐
- 品达通用权限系统(Day 1~Day 2)
- JSONUtils工具类(基于alibaba fastjson)
- Developer survey: rust/postgresql is the most popular, and PHP salary is low
- vue中缓存组件keep-alive
- 0基础学c语言(3)
- 郭明錤:苹果 AR / MR 头显是其有史以来设计最复杂的产品,将于 2023 年 1 月发布
- 刷新三观的HP-UX系统中的强指针赋值出core问题
- String string is converted to jsonarray and parsed
- MySQL - database creation and management
- The king of Internet of things protocol: mqtt
猜你喜欢

On the origin of the dispute between the tradition and the future of database -- AWS series column

(树) 树状数组

mysql的充值问题

MySQL - subquery usage

Development of NFT for digital collection platform

Detailed explanation of retrospective thinking

IK分词器

MySQL recharge

Web resource preloading - production environment practice

Detailed explanation of shutter textfield
随机推荐
【最详细】最新最全Redis面试大全(70道)
动态规划111
Gd32 USB composite device file descriptor
超分之VRT
Tiktok practice ~ sharing module ~ short video download (save to photo album)
Chain game development finished product source code chain game system development details
Is it safe to open a securities account? Is there any danger
Guomingyu: Apple's AR / MR head mounted display is the most complicated product in its history and will be released in January 2023
网上办理中金财富开户安全吗?
515. 在每个树行中找最大值
Successfully solved the problem of garbled microservice @value obtaining configuration file
swagger:如何生成漂亮的静态文档说明页
关于Qt数据库开发的一些冷知识
抖音实战~分享模块~复制短视频链接
問題解决:虛擬機無法複制粘貼文件
开发者调查:Rust/PostgreSQL 最受喜爱,PHP 薪水偏低
String string is converted to jsonarray and parsed
Flutter TextField详解
MongoDB实现创建删除数据库、创建删除表(集合)、数据增删改查
Jsonutils tool class (based on Alibaba fastjson)