手機版網(wǎng)站制作應(yīng)用淘寶如何刷關(guān)鍵詞增加權(quán)重
JWT的Token要經(jīng)過加密才能返回給客戶端,包括客戶端上傳的Tokn,后端項目需要驗證核
實。于是我們需要一個WT工具類,用來加密Token和驗證Token的有效性。
一、導(dǎo)入依賴
<dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>3.10.3</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.11</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.4.13</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency>
二、定義密鑰和過期時間
在application文件中加入,建議大家把密鑰和過期時間定義到Spring Boot配置文件中,然后再值注入到j(luò)avaBean中,這樣維護起來比較方便。
emos:jwt:#密鑰secret: abc123456#令牌過期時間(天)expire: 5#令牌緩存時間(天)cache-expire: 10
三、創(chuàng)建jwt工具類
@Component
@Slf4j
public class JwtUtil {@Value("${emos.jwt.secret}") //讀取的就是application文件中的數(shù)值private String secret;@Value("${emos.jwt.expire}")private int expire;//創(chuàng)建令牌private String createToken(int userId) {//根據(jù)expire算下過期時間在什么時候DateTime date = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, 5);//生成密鑰Algorithm algorithm= Algorithm.HMAC256(secret);//創(chuàng)建內(nèi)部類綁定userid,密鑰和過期時間JWTCreator.Builder builder= JWT.create();builder.withClaim("userId", userId);builder.withExpiresAt(date);//生成的令牌String token = builder.sign(algorithm);return token;}//從令牌對象反向獲取useridpublic int getUserId(String token) {DecodedJWT jwt = JWT.decode(token);Integer userId = jwt.getClaim("userId").asInt();return userId;}//驗證令牌有效性public void verifyToken(String token) {//驗證令牌內(nèi)容有效性 創(chuàng)建算法對象Algorithm algorithm = Algorithm.HMAC256(token);//創(chuàng)建驗證對象JWTVerifier build = JWT.require(algorithm).build();//驗證token是否有問題build.verify(token);}
}