jjwt 简单使用---Java
jjwt 简单使用---Java
<dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency>
package com.example.fei.service; import io.jsonwebtoken.Claims; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.stereotype.Component; import java.util.Date; /** * 参考资料: * https://github.com/jwtk/jjwt * https://stormpath.com/blog/jwt-java-create-verify */ @Component public class TokenService { private final static String myApiKeySecret = "fei_Secret_123456"; // 这里写入你的Secret /** * 创建 token * @return {} */ public String createToken() { long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); Date exp = new Date(nowMillis + 1000 * 30); // 过期时间 30秒 SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; // 签名算法 JwtBuilder builder = Jwts.builder() .setId("fei123") // 置唯一编号 // .setIssuedAt(now) //设置签发日期 // .setExpiration(exp) // 设置过期时间 // .setAudience("iot") // .setIssuer("fei") // 设置发行人 .setSubject( "fei_setSubject" ) .claim("userName", "username_01") .claim("userPwd", "123456") .signWith(signatureAlgorithm, myApiKeySecret); // 设置签名 使用HS256算法,并设置SecretKey(字符串) return builder.compact(); } /** * 校验 token 是否正确 * @param jwt String 用createToken方法中的返回值 * @return {} */ public Boolean parseJWT(String jwt) { try { Claims claims = Jwts.parser() .setSigningKey(myApiKeySecret) .parseClaimsJws(jwt) .getBody(); Object userName = claims.get("userName"); Object userPwd = claims.get("userPwd"); String subject = claims.getSubject(); System.out.println(userName.toString()); System.out.println(userPwd.toString()); System.out.println(subject); return true; } catch (Exception e) { System.out.println("Token格式有误"); return false; } } }
footer底部