日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

jwt工具类介绍

發布時間:2024/4/13 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 jwt工具类介绍 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

搭建授權中心

用戶鑒權:

  • 接收用戶的登錄請求,通過用戶中心的接口進行校驗,通過后生成JWT

  • 使用私鑰生成JWT并返回

有一些生成jwt,解析jwt這樣行為的工具類,以后在其它微服務中也會用到,因此放在gmall-core中。

JWT工具類

package com.leon.core.utils;import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.security.Keys; import org.joda.time.DateTime;import java.security.PrivateKey; import java.security.PublicKey; import java.util.Map;public class JwtUtils {/*** 私鑰加密token** @param map 載荷中的數據* @param expireMinutes 過期時間,單位秒* @return* @throws Exception*/public static String generateToken(Map<String, Object> map, PrivateKey key, int expireMinutes) throws Exception {return Jwts.builder().setClaims(map).setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate()).signWith(key, SignatureAlgorithm.RS256).compact();}/*** 公鑰解析token** @param token 用戶請求中的token* @return* @throws Exception*/private static Jws<Claims> parserToken(String token, PublicKey key) {return Jwts.parser().setSigningKey(key).parseClaimsJws(token);}/*** 獲取token中的用戶信息** @param token 用戶請求中的令牌* @return 用戶信息* @throws Exception*/public static Map<String, Object> getInfoFromToken(String token, PublicKey key) throws Exception {Jws<Claims> claimsJws = parserToken(token, key);return claimsJws.getBody();}} package com.leon.core.utils;import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.security.*; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec;public class RsaUtils {/*** 從文件中讀取公鑰** @param filename 公鑰保存路徑,相對于classpath* @return 公鑰對象* @throws Exception*/public static PublicKey getPublicKey(String filename) throws Exception {byte[] bytes = readFile(filename);return getPublicKey(bytes);}/*** 從文件中讀取密鑰** @param filename 私鑰保存路徑,相對于classpath* @return 私鑰對象* @throws Exception*/public static PrivateKey getPrivateKey(String filename) throws Exception {byte[] bytes = readFile(filename);return getPrivateKey(bytes);}/*** 獲取公鑰** @param bytes 公鑰的字節形式* @return* @throws Exception*/public static PublicKey getPublicKey(byte[] bytes) throws Exception {X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);KeyFactory factory = KeyFactory.getInstance("RSA");return factory.generatePublic(spec);}/*** 獲取密鑰** @param bytes 私鑰的字節形式* @return* @throws Exception*/public static PrivateKey getPrivateKey(byte[] bytes) throws Exception {PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);KeyFactory factory = KeyFactory.getInstance("RSA");return factory.generatePrivate(spec);}/*** 根據密文,生存rsa公鑰和私鑰,并寫入指定文件** @param publicKeyFilename 公鑰文件路徑* @param privateKeyFilename 私鑰文件路徑* @param secret 生成密鑰的密文* @throws IOException* @throws NoSuchAlgorithmException*/public static void generateKey(String publicKeyFilename, String privateKeyFilename, String secret) throws Exception {KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");SecureRandom secureRandom = new SecureRandom(secret.getBytes());keyPairGenerator.initialize(2048, secureRandom);KeyPair keyPair = keyPairGenerator.genKeyPair();// 獲取公鑰并寫出byte[] publicKeyBytes = keyPair.getPublic().getEncoded();writeFile(publicKeyFilename, publicKeyBytes);// 獲取私鑰并寫出byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();writeFile(privateKeyFilename, privateKeyBytes);}private static byte[] readFile(String fileName) throws Exception {return Files.readAllBytes(new File(fileName).toPath());}private static void writeFile(String destPath, byte[] bytes) throws IOException {File dest = new File(destPath);if (!dest.exists()) {dest.createNewFile();}Files.write(dest.toPath(), bytes);} }

并在core的pom.xml中引入新的依賴:

<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt-api</artifactId><version>0.10.6</version> </dependency> <dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt-impl</artifactId><version>0.10.6</version> </dependency> <dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt-jackson</artifactId><version>0.10.6</version><scope>runtime</scope> </dependency> <dependency><groupId>joda-time</groupId><artifactId>joda-time</artifactId><version>2.10.3</version> </dependency>

測試工具類

public class JwtTest {private static final String pubKeyPath = "C:\\tmp\\rsa\\rsa.pub";private static final String priKeyPath = "C:\\tmp\\rsa\\rsa.pri";private PublicKey publicKey;private PrivateKey privateKey;@Testpublic void testRsa() throws Exception {RsaUtils.generateKey(pubKeyPath, priKeyPath, "234");}@Beforepublic void testGetRsa() throws Exception {this.publicKey = RsaUtils.getPublicKey(pubKeyPath);this.privateKey = RsaUtils.getPrivateKey(priKeyPath);}@Testpublic void testGenerateToken() throws Exception {Map<String, Object> map = new HashMap<>();map.put("id", "11");map.put("username", "liuyan");// 生成tokenString token = JwtUtils.generateToken(map, privateKey, 5);System.out.println("token = " + token);}@Testpublic void testParseToken() throws Exception {String token = "eyJhbGciOiJSUzI1NiJ9.eyJpZCI6IjExIiwidXNlcm5hbWUiOiJsaXV5YW4iLCJleHAiOjE1NzAxMjEyODZ9.GioCiqMt_ZcN6_RAuDBcOzcHQ5WdqdhA9QYu-2IqCQqnAef1VyXczEInj1Ef1xo7AvcjxnkIMuZK48OoczUy1iqtPQPDchUzTl03b8h_J3xMBaxOAaKSwMpm20DH25VrTgBExUafyxHwxfOa-PVHW0Kk41KrWDncayzXbZ_lYLoa9Cuvacr8eAFz-ckriIiZ9bRzFkhX-wYHSHFlym2IJRjBRhFtpkN5GLAVsmsdm-yD4eiJXqioWspqXiBSdROsjrTRiFe511yujR0y2ngL9OnZ1QH6bHDQ2WmhPTrswKjjy-HWIxk1FQ7uXtSpPa5diymmPVTWA0clys7R1MK9oQ";// 解析tokenMap<String, Object> map = JwtUtils.getInfoFromToken(token, publicKey);System.out.println("id: " + map.get("id"));System.out.println("userName: " + map.get("username"));} }

測試生成公鑰和私鑰,我們運行這段代碼:**注意需要把@Before方法注釋掉

運行之后,查看目標目錄:

測試生成token,把@Before的注釋去掉的:

測試解析token:

正常情況:

任意改動一下:

?

超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生

總結

以上是生活随笔為你收集整理的jwt工具类介绍的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。