java jwt token生成和验证代码
时间: 2023-08-30 17:10:16 浏览: 131
JWT Token生成及验证
可以直接回答,以下是示例代码:
生成JWT Token:
```
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
public class JwtUtil {
private static final long EXPIRE_TIME = 5 * 60 * 1000;
private static final String SECRET_KEY = "your-secret-key";
public static String generateToken(String username) {
Date now = new Date();
Date expireTime = new Date(now.getTime() + EXPIRE_TIME);
return Jwts.builder()
.setSubject(username)
.setIssuedAt(now)
.setExpiration(expireTime)
.signWith(SignatureAlgorithm.HS256, SECRET_KEY)
.compact();
}
}
```
验证JWT Token:
```
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
public class JwtUtil {
private static final String SECRET_KEY = "your-secret-key";
public static String getUsernameFromToken(String token) {
Claims claims = Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody();
return claims.getSubject();
}
public static boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
return true;
} catch (Exception e) {
return false;
}
}
}
```
阅读全文