java写一个token
时间: 2023-12-21 15:03:23 浏览: 60
下面是一个简单的 Java 实现 JWT Token 的示例:
```java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
public class JwtTokenGenerator {
private static final String SECRET_KEY = "my_secret_key"; // 加密秘钥
private static final long EXPIRATION_TIME = 86400000L; // token 过期时间,这里设置为 24 小时
public static String generateToken(String username) {
Date now = new Date();
Date expiration = new Date(now.getTime() + EXPIRATION_TIME);
return Jwts.builder()
.setSubject(username)
.setIssuedAt(now)
.setExpiration(expiration)
.signWith(SignatureAlgorithm.HS512, SECRET_KEY)
.compact();
}
public static boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
return true;
} catch (Exception ex) {
return false;
}
}
public static String getUsernameFromToken(String token) {
Claims claims = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
return claims.getSubject();
}
}
```
使用示例:
```java
public class JwtTokenGeneratorTest {
public static void main(String[] args) {
String token = JwtTokenGenerator.generateToken("test_user");
System.out.println(token);
boolean isValid = JwtTokenGenerator.validateToken(token);
System.out.println(isValid);
String username = JwtTokenGenerator.getUsernameFromToken(token);
System.out.println(username);
}
}
```
阅读全文