java jwt 工具类
时间: 2023-12-31 14:24:13 浏览: 142
以下是一个使用Java JWT工具类的示例:
```java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JwtUtils {
private static final String SECRET_KEY = "your-secret-key";
private static final long EXPIRATION_TIME = 3 * 1000L; // 3秒
public static String createJwt(Map<String, Object> claims) {
Date now = new Date();
Date expiration = new Date(now.getTime() + EXPIRATION_TIME);
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(now)
.setExpiration(expiration)
.signWith(SignatureAlgorithm.HS256, SECRET_KEY)
.compact();
}
public static Claims parseJwt(String jwt) {
return Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(jwt)
.getBody();
}
}
public class Main {
public static void main(String[] args) {
// 创建JWT
Map<String, Object> claims = new HashMap<>();
claims.put("username", "zss");
String jwt = JwtUtils.createJwt(claims);
System.out.println(jwt);
// 解析JWT
Claims parseJwt = JwtUtils.parseJwt(jwt);
Date issuedAt = parseJwt.getIssuedAt();
Date expiration = parseJwt.getExpiration();
System.out.println("令牌签发时间:" + issuedAt);
System.out.println("令牌过期时间:" + expiration);
}
}
```
阅读全文