【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import lombok.Data;
public class JwtUtils {
/**
* 密钥
*/
private static final String SECRET = "123456";
/**
* 过期时间:秒
*/
private static final int EXPIRE = 3600;
private static String clientId = "clientId";
/**
* 生成Token
* @param tokenSource
* @param expire
* @return String
* @throws Exception
*/
public static <T> String createToken(T tokenSource, int expire) throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("clientId", clientId);
String userInfo = JacksonUtils.obj2Str(tokenSource).isPresent()?JacksonUtils.obj2Str(tokenSource).get():null;
String token = "";
try {
token = JWT.create()
.withHeader(map)//头
.withClaim("userInfo", userInfo)
.withIssuedAt(new Date())//签名时间
.withExpiresAt(expireDate(expire))//过期时间
.sign(Algorithm.HMAC256(SECRET));//签名
}catch (Exception e){
throw new Exception("生成Token失败");
}
return token;
}
private static Date expireDate(int expire){
Calendar nowTime = Calendar.getInstance();
if (expire > 0){
nowTime.add(Calendar.SECOND, expire);
}else {
nowTime.add(Calendar.SECOND, EXPIRE);
}
return nowTime.getTime();
}
/**
* 验证Token
* @param token
* @return
* @throws Exception
*/
public static Map<String, Claim> verifyToken(String token)throws Exception{
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
DecodedJWT jwt = null;
try {
jwt = verifier.verify(token);
}catch (Exception e){
throw new Exception("凭证已过期,请重新登录");
}
return jwt.getClaims();
}
/**
* 解析Token
* @param token
* @return
*/
public static Map<String, Claim> parseToken(String token){
DecodedJWT decodedJWT = JWT.decode(token);
return decodedJWT.getClaims();
}
//测试
public static void main(String[] args){
try {
User request = new User();
request.setUserId("123456");
request.setUserName("asdf");
String token = JwtUtils.createToken(request,0);
System.out.println("token=" + token);
Map<String, Claim> map = JwtUtils.verifyToken(token);
for (Map.Entry<String, Claim> entry : map.entrySet()) {
if (entry.getValue().asString() != null) {
System.out.println(entry.getKey() + "=" + entry.getValue().asString());
} else {
System.out.println(entry.getKey() + "=" + entry.getValue().asDate());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Data
static class User {
private String userId;
private String userName;
}
}
导包
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.9.0</version>
</dependency>
来源:oschina
链接:https://my.oschina.net/lion1220/blog/3154503