前端根据token反解析出用户信息
use Tymon\JWTAuth\JWTAuth;
class VerifySign extends JWTAuth { public function getUserInfo($token) {
t
h
i
s
?
>
s
e
t
T
o
k
e
n
(
this->setToken(
this?>setToken(token); $user = $this->authenticate(); reutrn $user; } }
后端java jwt解析
public class JwtUtils {
public static String generalSubject(Info info){
JSONObject jo = new JSONObject();
jo.put("id", info.getId());
jo.put("userid", info.getUserid());
jo.put("key", info.getKey());
return jo.toJSONString();
}
public static String createJWT(String id, String issuer, String subject, long ttlMillis) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(Constant.JWT_SECRET);
Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
JwtBuilder builder = Jwts.builder().setId(id).setIssuedAt(now).setSubject(subject).setIssuer(issuer)
.signWith(signatureAlgorithm, signingKey);
if (ttlMillis >= 0) {
long expMillis = nowMillis + ttlMillis;
Date exp = new Date(expMillis);
builder.setExpiration(exp);
}
return builder.compact();
}
public static void parseJWT(String jwt) {
Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(Constant.JWT_SECRET))
.parseClaimsJws(jwt).getBody();
System.out.println("ID: " + claims.getId());
System.out.println("Subject: " + claims.getSubject());
System.out.println("Issuer: " + claims.getIssuer());
System.out.println("Expiration: " + claims.getExpiration());
}
}
下面是我传递参数的一个类Info(可参考):
public class Info {
private String id;
private String userid;
private String key;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
下面是一些默认的配置,比如说过期时间,秘钥等信息:
public class Constant
{
public static final String JWT_ID = "jwttest";
public static final String JWT_SECRET = "LLL blog";
public static final int JWT_TTL = 60*60*1000;
public static final int JWT_REFRESH_INTERVAL = 55*60*1000;
public static final int JWT_REFRESH_TTL = 12*60*60*1000;
}
到这里的话基本上配置就齐全了,然后就是我们的主函数:
public class Main {
public static void main(String[] args) throws Exception {
Info info = new Info();
info.setId("This is LLL blog");
info.setUserid("123456789");
info.setKey("LLL丶禾羊 blog key value");
String generalSubject = JwtUtils.generalSubject(info);
String token = JwtUtils.createJWT("oschina", "issuerdata", generalSubject, Constant.JWT_TTL);
System.out.println(token);
JwtUtils.parseJWT(token);
}
}
|