You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
1.6 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.zh.project0512.utils;
import io.jsonwebtoken.*;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@ConfigurationProperties(prefix = "jwt")
@Component
@Data
public class JwtUtil {
private String secret = "secret";
private long expire = 24*60*60;
/**
* 签发jwt
*
* @param id
* @return
*/
public String createJWT(String id) {
Date date = new Date();
Date expireDate = new Date(date.getTime() + expire*1000);
String jwt= Jwts.builder().setId(id) .setSubject("token")
.setExpiration(expireDate)
.signWith(SignatureAlgorithm.HS256,secret)
.compact();
return jwt;
}
/**
* 解析JWT
*
* @param jwt
* @return
*/
public Claims parseJWT(String jwt) {
try {
return Jwts.parser().setSigningKey(secret).parseClaimsJws(jwt).getBody();
}catch (Exception e){
return null;
}
}
/**
* 解析JWT 用户openid
*
* @param jwt
* @return
*/
public String parseOpenid(String jwt) {
try {
return Jwts.parser().setSigningKey(secret).parseClaimsJws(jwt).getBody().getId();
}catch (Exception e){
return null;
}
}
/**
* token是否过期
* @return true过期
*/
public boolean isTokenExpired(Date expiration) {
return expiration.before(new Date());
}
}