Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Java JWT 加密解密
package com.diaolizhi.mybatisdemo.utils;
import com.diaolizhi.mybatisdemo.domain.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
/**
* @program: mybatis-demo
* @description: 用户 JWT 加密解密工具
* @author: diaolizhi
* @create: 2018-11-18 21:37
**/
public class UserJWTUtils {
private final static String SUBJECT = "dlz";
private final static long EXPIRE = 1000*60*60*24*7;
private final static String APPSECRET = "dlz123";
public static String geneUserJsonToken(User user) {
if(user == null || user.getId() == null || user.getUsername() == null || user.getCity() == null) {
return null;
}
String token = Jwts.builder()
// 设置发布者
.setSubject(SUBJECT)
// 添加信息,不能添加敏感信息
.claim("id", user.getId())
.claim("username", user.getUsername())
.claim("city", user.getCity())
// 设置开始时间
.setIssuedAt(new Date())
// 设置过期时间
.setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
// 设置加密算法和密钥
.signWith(SignatureAlgorithm.HS256, APPSECRET)
.compact();
return token;
}
public static Claims checkJWTToken(String token) {
try {
final Claims claims = Jwts.parser()
.setSigningKey(APPSECRET)
.parseClaimsJws(token)
.getBody();
return claims;
} catch (Exception e) { }
return null;
}
}
package com.diaolizhi.mybatisdemo;
import com.diaolizhi.mybatisdemo.domain.User;
import com.diaolizhi.mybatisdemo.utils.UserJWTUtils;
import io.jsonwebtoken.Claims;
import org.junit.Test;
/**
* @program: mybatis-demo
* @description: 测试 JWT
* @author: diaolizhi
* @create: 2018-11-18 21:51
**/
public class JWTTest {
@Test
public void testJWT() {
User user = new User();
user.setId(66);
user.setUsername("赵六");
user.setCity("广西");
String token = UserJWTUtils.geneUserJsonToken(user);
System.out.println(token);
}
@Test
public void testCheckJWT() {
String token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJkbHoiLCJpZCI6NjYsInVzZXJuYW1lIjoi6LW15YWtIiwiY2l0eSI6IuW5v-ilvyIsImlhdCI6MTU0MjU0OTE4OCwiZXhwIjoxNTQzMTUzOTg4fQ.81rZO_SHU0dbKf8QQxRBUrK-5txD-LGD3OimHeePihE";
Claims claims = UserJWTUtils.checkJWTToken(token);
if (claims != null) {
User user = new User();
user.setId((Integer) claims.get("id"));
user.setUsername((String) claims.get("username"));
user.setCity((String) claims.get("city"));
System.out.println(user);
} else {
System.out.println("非法 token");
}
}
}
<!-- JWT相关 -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.