一、项目说明
基于spring boot框架基础上,通过maven构建项目基础依赖,实现JWT的简单DEMO示例。
二、项目代码
1. jwt工具类
package com.itstyle.jwt.common.util;@b@import io.jsonwebtoken.Claims;@b@import io.jsonwebtoken.ExpiredJwtException;@b@import io.jsonwebtoken.JwtBuilder;@b@import io.jsonwebtoken.Jwts;@b@import io.jsonwebtoken.SignatureAlgorithm;@b@import io.jsonwebtoken.SignatureException;@b@@b@import java.util.Date; @b@@b@import javax.crypto.SecretKey;@b@import javax.crypto.spec.SecretKeySpec;@b@@b@import org.bouncycastle.util.encoders.Base64;@b@@b@import com.itstyle.jwt.common.constant.SystemConstant;@b@import com.itstyle.jwt.common.entity.CheckResult;@b@ @b@public class JwtUtils {@b@@b@ /**@b@ * 签发JWT @b@ *@b@ */@b@ public static String createJWT(String id, String subject, long ttlMillis) {@b@ SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;@b@ long nowMillis = System.currentTimeMillis();@b@ Date now = new Date(nowMillis);@b@ SecretKey secretKey = generalKey();@b@ JwtBuilder builder = Jwts.builder()@b@ .setId(id)@b@ .setSubject(subject) // 主题@b@ .setIssuer("小木人印象网") // 签发者@b@ .setIssuedAt(now) // 签发时间@b@ .signWith(signatureAlgorithm, secretKey); // 签名算法以及密匙@b@ if (ttlMillis >= 0) {@b@ long expMillis = nowMillis + ttlMillis;@b@ Date expDate = new Date(expMillis);@b@ builder.setExpiration(expDate); // 过期时间@b@ }@b@ return builder.compact();@b@ }@b@ /**@b@ * 验证JWT@b@ * @param jwtStr@b@ * @return@b@ */@b@ public static CheckResult validateJWT(String jwtStr) {@b@ CheckResult checkResult = new CheckResult();@b@ Claims claims = null;@b@ try {@b@ claims = parseJWT(jwtStr);@b@ checkResult.setSuccess(true);@b@ checkResult.setClaims(claims);@b@ } catch (ExpiredJwtException e) {@b@ checkResult.setErrCode(SystemConstant.JWT_ERRCODE_EXPIRE);@b@ checkResult.setSuccess(false);@b@ } catch (SignatureException e) {@b@ checkResult.setErrCode(SystemConstant.JWT_ERRCODE_FAIL);@b@ checkResult.setSuccess(false);@b@ } catch (Exception e) {@b@ checkResult.setErrCode(SystemConstant.JWT_ERRCODE_FAIL);@b@ checkResult.setSuccess(false);@b@ }@b@ return checkResult;@b@ }@b@ public static SecretKey generalKey() {@b@ byte[] encodedKey = Base64.decode(SystemConstant.JWT_SECERT);@b@ SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");@b@ return key;@b@ }@b@ @b@ /**@b@ * @b@ * 解析JWT字符串@b@ * @param jwt@b@ * @return@b@ * @throws Exception@b@ */@b@ public static Claims parseJWT(String jwt) throws Exception {@b@ SecretKey secretKey = generalKey();@b@ return Jwts.parser()@b@ .setSigningKey(secretKey)@b@ .parseClaimsJws(jwt)@b@ .getBody();@b@ }@b@@b@ public static void main(String[] args) throws Exception {@b@// //张三失效 10s@b@// String sc = createJWT("1","张三", 300000);@b@// System.out.println(sc);@b@// System.out.println(validateJWT(sc).getErrCode());@b@// System.out.println(validateJWT(sc).getClaims().getId());@b@// //Thread.sleep(3000);@b@// System.out.println(validateJWT(sc).getClaims());@b@@b@@b@@b@@b@@b@ }@b@}
三、运行测试结果
浏览器调用测试登录接口http://localhost:8080/spring-boot-jwt/login?username=abc&password=123456
{"msg":"eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxIiwic3ViIjoiYWJjIiwiaXNzIjoi5bCP5pyo5Lq65Y2w6LGh572RIiwiaWF0IjoxNjUwMzc2MTY1LCJleHAiOjE2NTAzNzk3NjV9.BIuUsRrpXolyfAL-w6Bt8qPivcK_BSnxjUaLhLqwqCk","code":0}