Spring boot使用JWT
1.pom文件引入依赖:
<!--jwt依赖-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.1.0</version>
</dependency>
2.创建JwtUtils工具类:
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Component
public class GatewayJwtUtil {
/**
* 加密算法中加的盐
*/
private static final String SECRET = "9a96349";
/**
* 用户,发布人
*/
private static String ISSUER = "sys_user";
/**
* 生成token
* @param claims 传入参数
* @return String
*/
public String genToken(Map<String, String> claims){
String token;
//发布时间
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
// 生成JWT过期的时间
long ttlMillis = nowMillis + 24L * 60L * 3600L * 1000L;
Date expTime = new Date(ttlMillis);
try {
//使用HMAC256进行加密
Algorithm algorithm = Algorithm.HMAC256(SECRET);
//创建jwt,添加发行人,发布的时间点
JWTCreator.Builder builder = JWT.create()
.withIssuer(ISSUER)
.withIssuedAt(expTime)
.withIssuedAt(now);
//传入参数
claims.forEach((key,value)-> {
builder.withClaim(key, value);
});
//签名加密
token = builder.sign(algorithm);
} catch (IllegalArgumentException | UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return token;
}
/**
* 解密jwt
* @param token token
* @return Map
* @throws RuntimeException 运行时异常
*/
public Map<String,String> verifyToken(String token) throws RuntimeException{
Algorithm algorithm = null;
try {
//使用HMAC256进行加密
algorithm = Algorithm.HMAC256(SECRET);
} catch (IllegalArgumentException | UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
//解密
JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
DecodedJWT jwt = verifier.verify(token);
Map<String, Claim> map = jwt.getClaims();
Map<String, String> resultMap = new HashMap<>();
map.forEach((k,v) -> resultMap.put(k, v.asString()));
return resultMap;
}
}
3.测试工具类:
{
Map<String,String> map = new HashMap<>(16);
map.put("name","张三");
map.put("sex","男");
String token = jwtUtil.genToken(map);
System.out.println(token);
map = jwtUtil.verifyToken(token);
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
}
}
运行截图:
打开 https://jwt.io/ 进行JWT验证。
对于JWT更为重要的是对JWT的理解,实战中使用还需要多多了解更多的知识