jwt 生成token 和解析token

阅读更多
0.6.0
1.2.16
      
    io.jsonwebtoken
    jjwt
    ${jjwt.version}



    com.alibaba
    fastjson
    ${fastjson.version}


代码:


import java.io.Serializable;

public class User implements Serializable{

private static final long serialVersionUID = -8036219797322639507L;

private String account;
private String pwd;
private Long userId;
private Long roleId;

public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}



package io.gjp.util;

import java.util.Date;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import io.gjp.User;
import io.gjp.config.Constant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Header;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

@Component
public class JwtUtil {

@Value("${spring.profiles.active}")
private String profiles;

/**
* 由字符串生成加密key
*
* @return
*/
public SecretKey generalKey() {
String stringKey = profiles + Constant.JWT_SECRET;
byte[] encodedKey = Base64.decodeBase64(stringKey);
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
return key;
}

/**
* 创建jwt
*
* @param id
* @param subject
* @param ttlMillis
* @return
* @throws Exception
*/
public String createJWT(String id, String subject, long ttlMillis) throws Exception {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
SecretKey key = generalKey();
JwtBuilder builder = Jwts.builder().setId(id).setIssuedAt(now).setSubject(subject).signWith(signatureAlgorithm,
key);
if (ttlMillis >= 0) {
long expMillis = nowMillis + ttlMillis;
Date exp = new Date(expMillis);
builder.setExpiration(exp);
}
return builder.compact();
}

/**
* 解密jwt
*
* @param jwt
* @return
* @throws Exception
*/
public Claims parseJWT(String jwt) throws Exception {
SecretKey key = generalKey();
Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody();
return claims;
}

/**
* 生成subject信息
*
* @param user
* @return
*/
public static String generalSubject(User user) {
JSONObject jo = new JSONObject();
jo.put("userId", user.getUserId());
jo.put("roleId", user.getRoleId());
return jo.toJSONString();
}

/**
* 创建jwt
*
* @param id
* @param subject
* @param ttlMillis
* @return
* @throws Exception
*/
public String createJWT2(String id, String subject, long ttlMillis) throws Exception {


SecretKey key = getkey2();

SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
JwtBuilder builder = Jwts.builder()
.setId(id).setIssuedAt(now).setSubject(subject).signWith(signatureAlgorithm,
key);
if (ttlMillis >= 0) {
long expMillis = nowMillis + ttlMillis;
Date exp = new Date(expMillis);
builder.setExpiration(exp);
}
return builder.compact();
}

/**
* 解密jwt
*
* @param jwt
* @return
* @throws Exception
*/
public Claims parseJWT2(String jwt) throws Exception {
SecretKey key = getkey2();
Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody();
return claims;
}

public SecretKey getkey2() {
String stringKey = "test" + Constant.JWT_SECRET;
byte[] encodedKey = Base64.decodeBase64(stringKey);
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
return key;
}

public static void main(String[] args) {
User user = new User();
user.setUserId(993456L);
user.setRoleId(12L);
user.setAccount("account");

String subject = JwtUtil.generalSubject(user);

JwtUtil jwt = new JwtUtil();
try {
String token = jwt.createJWT2(Constant.JWT_ID, subject, Constant.JWT_TTL);

System.out.println("token:"+token);
           // token="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJqd3QiLCJpYXQiOjE0OTY3MzU2MjMsInN1YiI6IntcInVzZXJJZFwiOjEyMzQ1NixcInJvbGVJZFwiOjEyfSIsImV4cCI6MTQ5NjczOTIyM30.Hoxvzo7iexB4KZspVrVIEC1rhUKiwFaPkEveT2OEudU";
   System.out.println("解析token:");
Claims claims = jwt.parseJWT2(token);
String json = claims.getSubject();
System.out.println("json User:"+json);
System.out.println("id:"+claims.getId());
System.out.println("Expiration:"+claims.getExpiration());

User user2 = JSONObject.parseObject(json, User.class);
System.out.println("userId"+user2.getUserId());
} catch (Exception e) {
e.printStackTrace();
}

}
}



运行结果:
token:eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJqd3QiLCJpYXQiOjE0OTY3Mzg4MDQsInN1YiI6IntcInVzZXJJZFwiOjk5MzQ1NixcInJvbGVJZFwiOjEyfSIsImV4cCI6MTQ5Njc0MjQwNH0.SohDpY2cyIY_vW0jMOMl_WoqoOfuXO75oyc6mEFYEdE
解析token:
json User:{"userId":993456,"roleId":12}
id:jwt
Expiration:Tue Jun 06 17:46:44 CST 2017
userId993456

你可能感兴趣的:(jwt,token)