@@ -34,123 +34,26 @@ implementation group: 'com.google.code.gson', name: 'gson', version: '2.11.0'
3434```
3535
3636### 创建配置文件:
37- 代码:jwt.properties
38-
39- ``` bash
40- jwt.secret=" 12345678901234567890123456789012345678901234567890123456789012345678901234567890"
41- jwt.iss=" ISS_qianfafang"
42- jwt.sub=" SUBJECT_zhuti"
43- # jwt.aud="ADU_jieshoufang"
44- # jwt.exp="EXP_chaoshitime"
45- # jwt.nbf="NBF_starttime"
46- # jwt.iat="IAT_qianfatime"
47- # jwt.jti="JTI_onlyID"
48- ```
49-
50-
51- ### JWT工具类-JWTUtil:
52- 代码:com/jinwei/{项目根目录}/JWTUtil.java
53-
54- ``` java
55- package com.jinwei.S8_mongotemplate ;
56-
57- import io.jsonwebtoken.* ;
58- import lombok.Data ;
59- import javax.crypto.SecretKey ;
60- import java.util.Date ;
61- import java.util.UUID ;
62- import io.jsonwebtoken.Jwts ;
63- import io.jsonwebtoken.security.Keys ;
64- import io.jsonwebtoken.security.SecureDigestAlgorithm ;
65- import org.springframework.beans.factory.annotation.Value ;
66- import org.springframework.context.annotation.Configuration ;
67- import org.springframework.context.annotation.PropertySource ;
68- import java.time.Instant ;
69-
70- @Data
71- @PropertySource (value = { " jwt.properties" })
72- @Configuration
73- public class JWTUtil {
74- // 设置token访问的过期时间-单位/分种
75- private static final int MINUTE = 60 ;
76- public static final int ACCESS_EXPIRE = 1 * MINUTE ;
77-
78- // 设置秘钥的加密算法
79- private final static SecureDigestAlgorithm<SecretKey , SecretKey > ALGORITHM = Jwts . SIG. HS512 ;
80- // 生成私钥,只能在服务器端保存
81- // 使用Jwts.SIG.HS256 算法需要SECRET至少32位
82- // 使用Jwts.SIG.HS512 算法需要SECRET至少64位
83- // 设置密钥字符串
84- private static String SECRET = " SECRET" ;
85-
86- // 使用加密算法加密密钥字符串
87- public static final SecretKey KEY = Keys . hmacShaKeyFor(SECRET . getBytes());
88-
89- // 设置jwt签发者
90- private static String JWT_ISS ;
91-
92- // 设置jwt主题
93- private static String = " SUBJECT" ;
94-
95- /* 常用声明:
96- iss: jwt签发者-签发方
97- sub: jwt主题-面向用户
98- aud: jwt接受者-接受方
99- exp: jwt过期时间-过期时间必须要大于签发时间
100- nbf: jwt开始启用时间-定义在什么时间之前-jwt不可用的
101- iat: jwt签发时间-过期时间必须要大于签发时间
102- jti: jwt唯一身份标识-主要用来作为一次性token-回避重放攻击
103- */
104- public static String genJWTToken (String inputStr ) {
105- // 生成令牌id-UUID.randomUUID()-随机
106- String uuid = UUID . randomUUID(). toString();
107- Date exprireDate = Date . from(Instant . now(). plusSeconds(ACCESS_EXPIRE ));
108-
109- return Jwts . builder()
110- // 设置头部信息-header
111- .header()
112- .add(" type" , " JWT" )
113- .add(" algo" , " HS512" )
114- .and()
115- // 设置负载信息-payload
116- .claim(" username" , inputStr)
117- // 设置令牌ID
118- .id(uuid)
119- // 设置过期日期
120- .expiration(exprireDate)
121- // 设置签发时间
122- .issuedAt(new Date ())
123- // 设置主题
124- .subject(SUBJECT )
125- // 设置签发者
126- .issuer(JWT_ISS )
127- // 设置签名
128- .signWith(KEY , ALGORITHM )
129- .compact();
130- }
131-
132- // 解析token-claim
133- public static Jws<Claims > parseClaim (String token ) {
134- return Jwts . parser()
135- .verifyWith(KEY ) // 必须持有相同的KEY才能解析
136- .build()
137- .parseSignedClaims(token);
138- }
139-
140- // 解析头部-Header
141- public static JwsHeader parseHeader (String token ) {
142- return parseClaim(token). getHeader();
143- }
144-
145- // 解析负载-Payload
146- public static Claims parsePayload (String token ) {
147- return parseClaim(token). getPayload();
148- }
149-
37+ 代码:com/jinwei/{资源目录=resources}/jwt-authorization.json
38+
39+ ![ alt text] ( image-65.png )
40+
41+ ``` json
42+ {
43+ "secret" : " 12345678901234567890123456789012345678901234567890123456789012345678901234567890" ,
44+ "iss" : " ISS_qianfafang" ,
45+ "subject" : " SUBJECT_zhuti" ,
46+ "aud" : " ADU_jieshoufang" ,
47+ "exp" : " EXP_chaoshitime" ,
48+ "nbf" : " NBF_starttime" ,
49+ "iat" : " IAT_qianfatime" ,
50+ "jti" : " JTI_onlyID"
15051}
15152```
15253
153- ### 更新JWT工具类-JWTUtil:
54+ 注意:所有配置可以一次性写入,JAVA读取的时候按照实例化的配置类 JWTConfig实际设置的参数进行选择读取,不需要考虑与json文件的对应配置。
55+
56+ ## JWT工具类-JWTUtil:
15457代码:com/jinwei/{项目根目录}/JWTUtil.java
15558
15659更新:添加了JSON配置参数文件的读取
@@ -272,6 +175,78 @@ public class JWTUtil {
272175}
273176```
274177
178+ ## JSON工具类-JsonUtil
179+ ``` java
180+ package com.jinwei.S8_mongotemplate ;
181+
182+ import com.alibaba.fastjson2.JSON ;
183+ import com.google.gson.Gson ;
184+ import com.google.gson.JsonElement ;
185+ import com.google.gson.JsonObject ;
186+
187+ import java.io.* ;
188+
189+ public class JsonUtil {
190+
191+ public String readJSON (String jsonFile ) throws IOException {
192+ // File file0 = new File("");
193+ // String filePath = file0.getCanonicalPath();
194+ // System.out.println("filePath = " + filePath);
195+
196+ // String oriPath = this.getClass().getResource("").getPath();
197+ // System.out.println("oriPath = " + oriPath);
198+
199+ File file01 = new File (" " );
200+ String filePath01 = file01. getAbsolutePath();
201+ // System.out.println("filePath01 = " + filePath01);
202+
203+ String dirPath = filePath01 + File . separator + " src" + File . separator + " main" + File . separator + " resources" + File . separator + jsonFile;
204+ // System.out.println("dirPath = " + dirPath);
205+
206+ File file = new File (dirPath);
207+ System . out. println(" file = " + file);
208+ FileReader fileReader = new FileReader (file);
209+
210+ Reader reader = new InputStreamReader (new FileInputStream (file), " Utf-8" );
211+ int ch = 0 ;
212+ StringBuffer sb = new StringBuffer ();
213+ while ((ch = reader. read()) != - 1 ) {
214+ sb. append((char ) ch);
215+ }
216+ fileReader. close();
217+ reader. close();
218+ String jsonStr = sb. toString();
219+ // System.out.println("jsonStr = " + jsonStr);
220+ // System.out.println("JSON.parseObject(jsonStr) = " + JSON.parseObject(jsonStr));
221+ return jsonStr;
222+ }
223+ }
224+ ```
225+
226+ ## 配置类-JWTConfig
227+ ```
228+ package com.jinwei.S8_mongotemplate;
229+
230+ public class JWTConfig
231+ {
232+ String secret;
233+ String iss;
234+ String subject;
235+
236+ @Override
237+ public String toString()
238+ {
239+ final StringBuilder sb = new StringBuilder("JWTConfig{");
240+ sb.append("secret='").append(secret).append('\'');
241+ sb.append(", iss=").append(iss);
242+ sb.append(", subject=").append(subject);
243+ sb.append('}');
244+ return sb.toString();
245+ }
246+ }
247+
248+ ```
249+
275250## 测试主文件
276251
277252``` java
@@ -305,5 +280,31 @@ public class S8MongotemplateApplication {
305280}
306281```
307282
283+ ## 测试
284+
285+ ``` bash
286+ 上午11:18:30: 正在执行 ' :S8MongotemplateApplication.main()' …
308287
288+ > Task :compileJava
289+ > Task :processResources
290+ > Task :classes
291+
292+ > Task :S8MongotemplateApplication.main ()
293+ file = F:\T utorial\S pringTest\K EY\S 8-mongotemplate\S 8-mongotemplate\s rc\m ain\r esources\j wt-authorization.json
294+ jwtoken = eyJ0eXBlIjoiSldUIiwiYWxnbyI6IkhTNTEyIiwiYWxnIjoiSFM1MTIifQ.eyJ1c2VybmFtZSI6Int9IiwianRpIjoiMDQwY2E1NmYtOTNjOC00OWNmLTg3YmMtMWUzYzkyMGNjOGRjIiwiZXhwIjoxNzIyNTY4NzcxLCJpYXQiOjE3MjI1Njg3MTEsInN1YiI6IlNVQkpFQ1Rfemh1dGkiLCJpc3MiOiJJU1NfcWlhbmZhZmFuZyJ9.MuY7xOlKIPxWefdHNWleOoPqI4U3Vj_oLi4hxhJ8BgPJm7JsuG0pVdBuGYN8z_ZW5iwakBLmdmPOu0boLR4spw
295+ jwtUtil.parseClaim(jwtoken) = header={type=JWT, algo=HS512, alg=HS512},payload={username={}, jti=040ca56f-93c8-49cf-87bc-1e3c920cc8dc, exp=1722568771, iat=1722568711, sub=SUBJECT_zhuti, iss=ISS_qianfafang},signature=MuY7xOlKIPxWefdHNWleOoPqI4U3Vj_oLi4hxhJ8BgPJm7JsuG0pVdBuGYN8z_ZW5iwakBLmdmPOu0boLR4spw
296+ jwtUtil.parsePayload(jwtoken) = {username={}, jti=040ca56f-93c8-49cf-87bc-1e3c920cc8dc, exp=1722568771, iat=1722568711, sub=SUBJECT_zhuti, iss=ISS_qianfafang}
297+
298+ Deprecated Gradle features were used in this build, making it incompatible with Gradle 9.0.
299+
300+ You can use ' --warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.
301+
302+ For more on this, please refer to https://docs.gradle.org/8.8/userguide/command_line_interface.html#sec:command_line_warnings in the Gradle documentation.
303+
304+ BUILD SUCCESSFUL in 1s
305+ 3 actionable tasks: 3 executed
306+ 上午11:18:32: 执行完成 ' :S8MongotemplateApplication.main()' 。
307+
308+ ` ` `
309309
310+ 测试成功!
0 commit comments