jwt简单介绍
·
jwt全称为jsonwebtoken,尤其在前后端分离的情形下,由于它自包含,轻量安全的特性常常使用在后端用户权限校验中。
jwt由三部分组成
1.头部(header) 常包含1加密算法 2token类型
2.载荷(payload) 包含颁发者,有效期等和用户自定义属性
3.签名
下面演示在Java中如何使用Jwt
1.引入依赖
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
2.新建工具类
public class JWTTest {
public static final String SECRET = "dkjfkjdfkljdf";
/** token 过期时间: 10天 */
public static final int calendarField = Calendar.DATE;
public static final int calendarInterval = 10;
/**
* JWT生成Token.<br/>
*
* JWT构成: header, payload, signature
*
* @param user_id
* 登录成功后用户user_id, 参数user_id不可传空
*/
public static String createToken(Long user_id) throws Exception {
Date iatDate = new Date();
// expire time
Calendar nowTime = Calendar.getInstance();
nowTime.add(calendarField, calendarInterval);
Date expiresDate = nowTime.getTime();
// header Map
Map<String, Object> header = new HashMap<>();
header.put("alg", "HS256");
header.put("typ", "JWT");
// build token
// param backups {iss:Service, aud:APP}
String token = JWT.create().withHeader(header) // header
.withClaim("iss", "Service") // payload
.withClaim("aud", "APP")
.withClaim("user_id", null == user_id ? null : user_id.toString())
.withIssuedAt(iatDate) // sign time
.withExpiresAt(expiresDate) // expire time
.sign(Algorithm.HMAC256(SECRET)); // signature
return token;
}
/**
* 解密Token
*
* @param token
* @return
* @throws Exception
*/
public static Map<String, Claim> verifyToken(String token) {
DecodedJWT jwt = null;
try {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
jwt = verifier.verify(token);
} catch (Exception e) {
throw new RuntimeException("token异常", e);
}
return jwt.getClaims();
}
/**
* 根据Token获取user_id
*
* @param token
* @return user_id
*/
public static Long getAppUID(String token) {
Map<String, Claim> claims = verifyToken(token);
Claim user_id_claim = claims.get("user_id");
if (null == user_id_claim || StringUtils.isEmpty(user_id_claim.asString())) {
// token 校验失败, 抛出Token验证非法异常
}
return Long.valueOf(user_id_claim.asString());
}
public static void main(String[] args) throws Exception {
String token = createToken(28L);
System.out.println("token:\n" + token);
Long appUID = getAppUID(token);
System.out.println("appUID = " + appUID);
}
}
更多推荐
所有评论(0)