| | |
| | | private long jwtExpiration; |
| | | |
| | | /** |
| | | * 生成JWT token |
| | | * 生成JWT token(旧版本,保持兼容性) |
| | | */ |
| | | public String generateToken(Long userId, String phone) { |
| | | return generateToken(userId, phone, null); |
| | | } |
| | | |
| | | /** |
| | | * 生成JWT token(新版本,支持wxopenid) |
| | | */ |
| | | public String generateToken(Long userId, String phone, String wxopenid) { |
| | | Date now = new Date(); |
| | | Date expiryDate = new Date(now.getTime() + jwtExpiration); |
| | | |
| | | SecretKey key = Keys.hmacShaKeyFor(jwtSecret.getBytes()); |
| | | |
| | | return Jwts.builder() |
| | | JwtBuilder builder = Jwts.builder() |
| | | .setSubject(userId.toString()) |
| | | .claim("phone", phone) |
| | | .setIssuedAt(now) |
| | | .setExpiration(expiryDate) |
| | | .signWith(key, SignatureAlgorithm.HS256) |
| | | .compact(); |
| | | .setExpiration(expiryDate); |
| | | |
| | | // 只有当phone不为null时才添加phone claim |
| | | if (phone != null) { |
| | | builder.claim("phone", phone); |
| | | } |
| | | |
| | | // 只有当wxopenid不为null时才添加wxopenid claim |
| | | if (wxopenid != null) { |
| | | builder.claim("wxopenid", wxopenid); |
| | | } |
| | | |
| | | return builder.signWith(key, SignatureAlgorithm.HS256).compact(); |
| | | } |
| | | |
| | | /** |
| | |
| | | } |
| | | |
| | | /** |
| | | * 从token中获取微信openid |
| | | */ |
| | | public String getWxOpenidFromToken(String token) { |
| | | Claims claims = getClaimsFromToken(token); |
| | | return claims.get("wxopenid", String.class); |
| | | } |
| | | |
| | | /** |
| | | * 验证token是否有效 |
| | | */ |
| | | public boolean validateToken(String token) { |