java JWT 生成和解析token
作者:互联网
采用 io.jsonwebtoken 版
导入maven
<dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> <version>0.11.2</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> <version>0.11.2</version> <scope>runtime</scope> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred --> <version>0.11.2</version> <scope>runtime</scope> </dependency>
实例
//生成token Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256); HashMap< String, Object > map = new HashMap<>( ); map.put("username", "张三"); map.put("password", "123456"); String token = Jwts.builder( ).setClaims(map).setExpiration(DateUtils.addDays(new Date( ), 1)).signWith(key).compact( ); //过期时间 System.err.println("token=" + token); //解析token Jws< Claims > claimsJws = Jwts.parserBuilder( ).setSigningKey(key).build( ).parseClaimsJws(token); Claims body = claimsJws.getBody( ); System.err.println(body.get("username")); System.err.println(body.get("password")); // .setIssuer("me") //发行人 // .setSubject("Bob") //项目 // .setAudience("you") //用户 // .setExpiration(expiration) //过期时间 // .setNotBefore(notBefore) //a java.util.Date // .setIssuedAt(new Date()) // 发行时间 // .setId(UUID.randomUUID()) //id
更多方法:https://github.com/jwtk/jjwt#asymmetric-keys
标签:body,map,java,JWT,jjwt,token,io,jsonwebtoken 来源: https://www.cnblogs.com/lccsdncnblogs/p/13898727.html