package mr.li.hello.demo;

import java.util.HashMap;
import java.util.Map;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JwtDemo {

public static String secret = "secret";

public static String token_prefix = "token前缀";

/**
* <pre>
* 生成jwt token
* </pre>
*
* @return
*/
public static String genertateToken() {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("id", "111111");
map.put("name", "龙哥");
String jwt = Jwts.builder().
setSubject("jwt中存放的用户数据")
.setClaims(map)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
return token_prefix + jwt;
}

/**
* <pre>解析jwt token</pre>
* @param token
* @return
*/
public static Map<String, String> validateToken(String token) {
Map<String, Object> map = Jwts.parser().setSigningKey(secret).parseClaimsJws(token.replace(token_prefix, ""))
.getBody();
String id = String.valueOf(map.get("id"));
String name = String.valueOf(map.get("name"));
Map<String, String> map1 = new HashMap<String, String>();
map1.put("id", id);
map1.put("name", name);
return map1;
}


public static void main(String[] args) {
String jwtToken = genertateToken();
Map<String, String> map = validateToken(jwtToken);
System.out.println(map);
}
}

 引入pom坐标

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.mr.li</groupId>
<artifactId>hello-world</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<!-- 父依赖为spring2.1.6 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<properties>
<jwt-version>0.7.0</jwt-version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>${jwt-version}</version>
</dependency>
</dependencies>

</project>