依赖
< dependency> < groupId> io.jsonwebtoken</ groupId> < artifactId> jjwt</ artifactId> < version> 0.9.1</ version> </ dependency>
JwtUtil.java
package com. nnutc. common. utils ; import io. jsonwebtoken. Claims ;
import io. jsonwebtoken. JwtBuilder ;
import io. jsonwebtoken. Jwts ;
import io. jsonwebtoken. SignatureAlgorithm ; import java. util. Date ;
import java. util. HashMap ;
import java. util. Map ; public class JwtUtil { private static final String SECRET_KEY = "1ost" ; private static final long EXPIRATION_TIME = 3600000 ; public static String generateToken ( String subject) { Map < String , Object > claims = new HashMap < > ( ) ; JwtBuilder builder = Jwts . builder ( ) . setClaims ( claims) . setSubject ( subject) . setIssuedAt ( new Date ( System . currentTimeMillis ( ) ) ) . setExpiration ( new Date ( System . currentTimeMillis ( ) + EXPIRATION_TIME) ) . signWith ( SignatureAlgorithm . HS512, SECRET_KEY) ; return builder. compact ( ) ; } public static boolean validateToken ( String token) { try { Jwts . parser ( ) . setSigningKey ( SECRET_KEY) . parseClaimsJws ( token) ; return true ; } catch ( Exception e) { return false ; } } public static String getSubjectFromToken ( String token) { Claims claims = Jwts . parser ( ) . setSigningKey ( SECRET_KEY) . parseClaimsJws ( token) . getBody ( ) ; return claims. getSubject ( ) ; }
}