JWT
JWT有什么用?
JSON Web Token,通过数字签名的方式,以JSON对象为载体,后续每个请求都包含JWT,系统在每次处理用户请求的之前,都要先进行JWT安全校验,通过之后再进行处理。
JWT的组成
JWT由3部分组成,用.拼接
xxxxx.yyyyy.zzzzz
这3部分分别是:
- {
- 'typ':'JWT',
- 'alg':'HS256'
- }
复制代码- {
- "sub":'1234567890',
- "name":'json',
- "admin":true
- }
复制代码- var encodedString = base64UrlEncode(header)+'.'+base64UrlEncode(payload);
- var signature =HMACSHA256(encodedString,'secret')
复制代码 配置依赖
- <dependency>
- <groupId>io.jsonwebtoken</groupId>
- <artifactId>jjwt</artifactId>
- <version>0.9.1</version>
- </dependency>
复制代码 测试:
- @Test
- public void jwt(){
- JwtBuilder jwtBuilder = Jwts.builder();
- String jwtToken =jwtBuilder
- //hearder
- .setHeaderParam("typ","JWT")
- .setHeaderParam("alg","HS256")
- //payload
- .claim("username","tom")
- .claim("role","admin")
- .setSubject("admin-test")
- .setExpiration(new Date(System.currentTimeMillis()+time))
- .setId(UUID.randomUUID().toString())
- //signature
- .signWith(SignatureAlgorithm.HS256,signature)
- //拼接
- .compact();
- System.out.println(jwtToken);
- }
复制代码 解析:- @Test
- public void testJwt(){
- String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRvbSIsInJvbGUiOiJhZG1pbiIsInN1YiI6ImFkbWluLXRlc3QiLCJleHAiOjE2NTQwNzIzMjksImp0aSI6IjIwZGY4NGQwLWZiODUtNGU0My04OWI4LWU5MWNjZWFkYTQ0MSJ9.ly3EZwqWHbUbdo7S4uHDRYo7husHDzoYS8g5AyA8BqM";
- JwtParser jwtParser = Jwts.parser();
- Jws<Claims> claimsJws = jwtParser.setSigningKey(signature).parseClaimsJws(token);
- Claims claims = claimsJws.getBody();
- System.out.println(claims.get("username"));
- System.out.println(claims.get("role"));
- System.out.println(claims.getId());
- //签名
- System.out.println(claims.getSubject());
- System.out.println(claims.getExpiration());
- }
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |