jwt 加密解密 需要一个 signkey ,这个是个 Base64 加密的任意字符串:
根据 https://stackoverflow.com/questions/33960565/how-to-generate-a-hs512-secret-key-to-use-with-jwt
使用下面命令生成即可:
dd if=/dev/random bs=129 count=1 status=none | base64
顺便附上 使用 io.jsonwebtoken 解析的代码:
生成 token
依赖:
<dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency>
java代码:
private static final long TOKEN_DURATION = 7 * 24 * 60 * 60 * 1000; @Value("${app.security.jwt.signingKey}") String signingKey; public String generateJWToken(Long uid) { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512; //生成JWT的时间 long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); Map<String, Object> claims = new HashMap<String, Object>(); claims.put("said", uid); List<String> authorities = new ArrayList<>(); authorities.add("ROLE_USER"); claims.put("said", uid); claims.put("authorities", authorities); JwtBuilder builder = Jwts.builder() .setClaims(claims) .setIssuedAt(now) .setSubject(String.valueOf(uid)) .signWith(signatureAlgorithm, signingKey); if (TOKEN_DURATION >= 0) { long expMillis = nowMillis + TOKEN_DURATION; Date exp = new Date(expMillis); builder.setExpiration(exp); } return builder.compact(); }
解析token
claims = Jwts.parser() .setSigningKey(signingKey) .parseClaimsJws(s) .getBody();