Json Web Token,通过数字签名的方式,以json对象为载体,在不同服务终端之间安全传递信息。
jwt作用jwt最常见的应用场景就是授权认证,一旦用户登录,后续每个请求都就要包含jwt,在每次处理用户请求之前都要进行jwt安全验证,验证通过才可以进行后续 *** 作。
jwt由三部分组成用“.”分割-
以下为jwt样式
-
eyJ0eXAiOiJKV1QiLCJhbHMiOiJIUzI1NiIsImFsZyI6IkhTMjU2In0.eyJ1c2VybmFtZSI6InRvbSIsInJvbGUiOiJhZG1pbiIsInN1YiI6ImRlbW8tdGVzdCIsImV4cCI6MTY1MTM4NzY2NSwianRpIjoiNjYxNTE2N2EtMTRhMC00ODQ4LWEyZDAtY2E0YjhjOTIxNzMzIn0.qR31lZECuK6OcR5Kp8KCNuNh8sRHAGbUtQBknOXUQwU
-
header
{ 'typ':'JWT', 'algs':'HS256' }
-
payload
{ 'username':'tome', 'role':'admin' }
-
signature
把header和payload转换成base64格式再用加密方式进行加密后生成第三部分
package com.xublog.demo;
import io.jsonwebtoken.*;
import java.util.Date;
import java.util.UUID;
public class JwtDemo {
private final static long time=1000*60*60*24;
private final static String signature="admin";
public String createJwt(){
JwtBuilder jwtBuilder= Jwts.builder();
return jwtBuilder
//header
.setHeaderParam("typ", "JWT")
.setHeaderParam("als", "HS2560")
//payload
.claim("username", "tom")
.claim("role", "admin")
.setSubject("demo-test")
.setExpiration(new Date(System.currentTimeMillis() + time))
.setId(UUID.randomUUID().toString())
//signature
.signWith(SignatureAlgorithm.HS256, signature)
//拼接起来
.compact();
}
public void parse(String token){
JwtParser parser = Jwts.parser();
Jws<Claims> claimsJws = parser.setSigningKey("admin").parseClaimsJws(token);
Claims body = claimsJws.getBody();
System.out.println(body.get("username")+""+body.getExpiration()+"-");
}
public static void main(String[] args) {
String token1 = new JwtDemo().createJwt();
String token2 = new JwtDemo().createJwt();
JwtDemo jwtDemo=new JwtDemo();
jwtDemo.parse(token1);
jwtDemo.parse(token2);
String token3="eyJ0eXAiOiJKV1QiLCJhbHMiOiJIUzI1NiIsImFsZyI6IkhTMjU2In0.eyJ1c2VybmFtZSI6InRvbSIsInJvbGUiOiJhZG1pbiIsInN1YiI6ImRlbW8tdGVzdCIsImV4cCI6MTY1MTM4NzY2NSwianRpIjoiNjYxNTE2N2EtMTRhMC00ODQ4LWEyZDAtY2E0YjhjOTIxNzMzIn0.qR31lZECuK6OcR5Kp8KCNuNh8sRHAGbUtQBknOXUQwU";
jwtDemo.parse(token3);
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)