JWT - Demo及原理
2021-03-13 本文已影响0人
夹胡碰
1. maven
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.1</version>
</dependency>
2. 代码
public class JWTDemo {
private static final String MY_SECRET = "mysecret";
public static void main(String[] args) {
User user = new User("123", "张三");
String token = getToken(user);
System.out.println(token);
User resultUser = verifyToken(token);
System.out.println(resultUser);
}
public static String getToken(User user){
return JWT.create()
.withClaim("id", user.getId())
.withClaim("name", user.getName())
// .withExpiresAt(new Date())
.sign(Algorithm.HMAC256(MY_SECRET));
}
public static User verifyToken(String token){
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(MY_SECRET)).build();
DecodedJWT jwt = verifier.verify(token);
Map<String, Claim> claims = jwt.getClaims();
return new User(claims.get("id").asString(), claims.get("name").asString());
}
public static class User{
private String id;
private String name;
public User(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}
}
3. 结果
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoi5byg5LiJIiwiaWQiOiIxMjMifQ.GP3ia_Ws2z9lXbEPLnI2CxpeBgi1YCf5LE9wlElZNXo
User{id='123', name='张三'}
可以在该网站上获得解析结果:https://jwt.io/
4. 说明
生成的token为三段 - Header,Payload,Signature
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoi5byg5LiJIiwiaWQiOiIxMjMifQ.GP3ia_Ws2z9lXbEPLnI2CxpeBgi1YCf5LE9wlElZNXo
- 第一段 - Header
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
通过Base64解密得
{"typ":"JWT","alg":"HS256"}
- 第二段 - Payload
eyJuYW1lIjoi5byg5LiJIiwiaWQiOiIxMjMifQ
通过Base64解密得
{"name":"张三","id":"123"}
- 第三段 - Signature
GP3ia_Ws2z9lXbEPLnI2CxpeBgi1YCf5LE9wlElZNXo
是通过第一段+"."+第二段通过HS256
加密得到的,此段做实际校验。