/*
采用JWT的生成TOKEN,及APP登录Token的生成和解析
*/
public class JwtTokenUtil {
/**
* token秘钥
*/
public static final String SECRET = "1234567890";
private static final String key = "user_code"; /**
* JWT生成Token.
* JWT构成: header, payload, signature
* @param userNo 登录成功后用户no, 参数no不可传空
*/
@Validated
public static String createToken(@NotBlank String userNo) throws Exception {
Date iatDate = new Date();
// expire time
Calendar nowTime = Calendar.getInstance();
nowTime.add(Calendar.DATE, 10);
Date expiresDate = nowTime.getTime(); // header Map
Map<String, Object> map = new HashMap<>();
map.put("alg", "HS256");
map.put("typ", "JWT"); // build token
// param backups {iss:Service, aud:APP}
String token = JWT.create().withHeader(map) // header
.withClaim("iss", "Service") // payload
.withClaim("aud", "APP")
.withClaim(key, userNo)
.withIssuedAt(iatDate) // sign time
.withExpiresAt(expiresDate) // expire time
.sign(Algorithm.HMAC256(SECRET)); // signature return token;
} /**
* 解密Token
* @param token
* @return
* @throws Exception
*/
private static Map<String, Claim> verifyToken(String token) {
DecodedJWT jwt = null;
try {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
jwt = verifier.verify(token);
} catch (Exception e) {
// e.printStackTrace();
// token 校验失败, 抛出Token验证非法异常
throw new BusinessException("token 验证失败");
}
return jwt.getClaims();
} /**
* 根据Token获取user_no
* @param token
* @return user_No
*/
public static String getAppUID(String token) {
Map<String, Claim> claims = verifyToken(token);
Claim user_id_claim = claims.get(key);
if (null == user_id_claim || StringUtils.isBlank(user_id_claim.asString())) {
// token 校验失败, 抛出Token验证非法异常
throw new BusinessException("token 异常");
}
return user_id_claim.asString();
}
}

最新文章

  1. http 各个状态码及对应的java 编程
  2. python 笔记1:安装python;eclipse中安装配置pydev
  3. 【Ubuntu日常技巧】VirtualBox多网卡路由配置,保障虚拟机连接上外网
  4. install kinect driver for ARM---38
  5. Hibernate O/R Mapping模拟
  6. Oracle INV - SO line backorder API
  7. [转载] ubuntu Authentication failure
  8. plupload上传控件错误exec(this.uid, component, action, args)
  9. Linux---More命令 初级实现
  10. uoj164. 【清华集训2015】V 统计
  11. 解决ios上微信无法捕获返回键按钮事件的问题
  12. storage theory
  13. Ubuntu中Qt新建窗体提示lGL错误
  14. 关于批量插入数据之我见(100万级别的数据,mysql) (转)
  15. C++/CLI泛型应用
  16. QQ的ldw值计算方法
  17. django基础 -- 4. 模板语言 过滤器 模板继承 FBV 和CBV 装饰器 组件
  18. Go parameter passing
  19. Git 使用SSH密钥操作
  20. mysql查询表基本操作

热门文章

  1. webconfig 配置 分离
  2. Mysql关键字之Group By(一)
  3. Clang的线程安全分析静态工具
  4. SNP功能注释网站合集
  5. TensorFlow.js-机器学习
  6. LODOP中的RightMargin右边距和BottomMargin下边距
  7. harbor镜像仓库-https访问配置
  8. python:校验邮箱格式
  9. 面试之哈希表leetcode
  10. (转)面试前必知Redis面试题—缓存雪崩+穿透+缓存与数据库双写一致问题