1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| import com.atguigu.security.entity.User; import io.jsonwebtoken.Claims; import io.jsonwebtoken.CompressionCodecs; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date; import java.util.HashMap; import java.util.Map;
public class JwtTokenManager {
private final String PRIVATE_KEY = "516Letitbe";
private final String ISSUER = "Letitbe";
private final long EXPIRATION_ONE_HOUR = 3600L;
private final long EXPIRATION_ONE_DAY = 3600 * 24;
public String createToken(User user, long expireTime) { if ( expireTime == 0 ) { expireTime = EXPIRATION_ONE_DAY; }
Map<String, Object> claims = new HashMap<>(); claims.put("id", user.getId()); claims.put("username", user.getUsername()); claims.put("password", user.getPassword());
String token = Jwts.builder() .setIssuer(ISSUER) .setClaims(claims) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + expireTime)) .signWith(SignatureAlgorithm.HS512, PRIVATE_KEY) .compressWith(CompressionCodecs.GZIP) .compact(); return token; }
public User getUserFromToken(String token) { Claims claims = getClaimsFromToken(token); String id = (String) claims.get("id"); String username = (String) claims.get("username"); String password = (String) claims.get("password"); User user = new User(); user.setId( id ); user.setUsername( username ); user.setPassword( password ); return user; }
public Claims getClaimsFromToken(String token){ Claims claims = null; try { claims = Jwts.parser() .setSigningKey(PRIVATE_KEY) .parseClaimsJws(token) .getBody(); }catch (Exception e){ return null; } return claims; } }
|