java jwt使用,springboot 整合java-jwt,java jwt工具类
2023-09-11 14:18:14 时间
java jwt使用,springboot 整合java-jwt,java jwt工具类
================================
©Copyright 蕃薯耀 2020-12-03
https://www.cnblogs.com/fanshuyao/
一、引入java-jwt的maven依赖
<dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.11.0</version> </dependency>
二、springboot自定义配置文件(jwt.properties)配置密钥
1、jwt.properties
jwt.key=and0X3ZhbGlkYXRpb25fY29uZmlnX2tleQ==
2、springboot自定义配置文件之类配置文件:JwtProperties.java,读取jwt.properties配置的密钥
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Configuration @PropertySource(value = {"jwt.properties"}, encoding = "UTF-8") @ConfigurationProperties(ignoreUnknownFields = true, prefix = "jwt") public class JwtProperties { private String key; public String getKey() { return key; } public void setKey(String key) { this.key = key; } }
三、java jwt工具类:JwtUtils.java
import java.text.ParseException; import java.util.Base64; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.JWTDecodeException; import com.auth0.jwt.exceptions.JWTVerificationException; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.exceptions.TokenExpiredException; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.lqy.study.exception.RunException; import com.lqy.study.utils.DateUtils; import cn.hutool.json.JSONUtil; @Component public class JwtUtils { private static Logger log = Logger.getLogger(JwtUtils.class); private static String secretKey; private static String KEY_JWT_CLAIMS = "key_jwt_claims"; private static String KEY_USER = "key_user"; private static String KEY_JAVA_JWT = "key_java_jwt"; private JwtUtils(){ } /** * 静态实体变量注入 * @param jwtProperties JwtProperties * jwtProperties需要配置:@ConfigurationProperties(prefix = "jwt", ignoreUnknownFields = true) */ @Autowired public void setSecretKey(JwtProperties jwtProperties) { JwtUtils.secretKey = jwtProperties.getKey(); } /** * 生成token * @return * @throws ParseException */ public static String getToken() throws ParseException { Date now = new Date(); Date expiresDate = DateUtils.addMinute(null, 2);//增加2分钟的过期时间,用于测试 log.info("now===" + DateUtils.formatDateTime(now)); log.info("expiresDate===" + DateUtils.formatDateTime(expiresDate)); User user = new User(); user.setId(1100L); user.setName("老王2"); Map<String, Object> claims = new HashMap<String, Object>(); claims.put(KEY_USER, user); Algorithm algorithm = getAlgorithm(); String token = JWT.create() //.withClaim(KEY_JWT_CLAIMS, user.getId())//claims不能是Map<String, Object> .withIssuer(KEY_JAVA_JWT) .withIssuedAt(now) .withHeader(claims) //.withKeyId(UUID.randomUUID().toString()) .withExpiresAt(expiresDate) .sign(algorithm); log.info("token===" + token); return token; } /** * 解析token,并返回User对象 * @param token * @return * @throws ParseException */ public static User parseToken(String token) throws ParseException { String msg = null; try { Algorithm algorithm = getAlgorithm(); JWTVerifier verifier = JWT.require(algorithm) .withIssuer(KEY_JAVA_JWT) .build(); DecodedJWT jwt = verifier.verify(token); String payload = jwt.getPayload(); Map<String, Claim> claims = jwt.getClaims(); User user = jwt.getHeaderClaim(KEY_USER).as(User.class); Long userId = claims.get(KEY_JWT_CLAIMS) == null ? null : claims.get(KEY_JWT_CLAIMS).asLong(); log.info("payload===" + payload); log.info("claims===" + JSONUtil.toJsonStr(claims)); log.info("userId===" + JSONUtil.toJsonStr(userId)); log.info("user===" + JSONUtil.toJsonStr(user)); return user; }catch (JWTDecodeException de) { msg = "密钥格式不正确"; log.error(msg, de); throw new RunException(msg); }catch (SignatureVerificationException de) { msg = "密钥签证不正确"; log.error(msg, de); throw new RunException(msg); }catch (TokenExpiredException tee) { msg = "密钥已过期"; log.error(msg, tee); throw new RunException(msg); }catch (InvalidClaimException ice) { msg = "非法密钥"; log.error(msg, ice); throw new RunException(msg); }catch (JWTVerificationException jwte) { msg = "密钥解析错误"; log.error(msg, jwte); throw new RunException(msg); } } /** * 获取自定义密钥 * @return */ private static Algorithm getAlgorithm(){ return Algorithm.HMAC256(getSecretKeyString()); } /** * 获取自定义密钥 * @return */ private static byte[] getSecretKey(){ //log.info("secretKey===" + secretKey); if(StringUtils.isBlank(secretKey)) { throw new RunException("jwt配置的密钥不能为空"); } return Base64.getDecoder().decode(secretKey); } /** * 获取自定义密钥 * @return */ private static String getSecretKeyString(){ String secretKeyString = new String(getSecretKey()); //log.info("secretKeyString===" + secretKeyString); return secretKeyString; } public static void main(String[] args) throws Exception { getToken(); } }
User类:
public class User { private Long id; private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User [id=" + id + ", name=" + name + "]"; } }
四、java jwt获取token和token验证
import java.text.ParseException; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.lqy.study.bean.Result; import com.lqy.study.biz.jjwt.JwtUtils; @RestController @RequestMapping("/jwt") public class JwtController { @RequestMapping("/get") public Result get() throws ParseException { return Result.ok(JwtUtils.getToken()); } @RequestMapping("/parse") public Result parse(String token) throws ParseException { return Result.ok(JwtUtils.parseToken(token)); } }
java jjwt-api使用见:
https://www.cnblogs.com/fanshuyao/p/14072358.html
(如果文章对您有帮助,欢迎捐赠,^_^)
================================
©Copyright 蕃薯耀 2020-12-03
https://www.cnblogs.com/fanshuyao/
相关文章
- Java GUI setSize()、setPreferredSize()的区别
- Java图片加水印
- 技术部突然宣布:JAVA开发人员全部要会接口自动化测试框架
- java 程序员 和 三八女神节有什么神秘的关系,你晓得吗? 用Java 给女神绘制一张贺卡你会吗?
- Java语言的特点
- Java Date Time 教程-java.util.Date
- Java8 Nashorn实现Java调用javascript代码
- access denied ("java.net.SocketPermission" "localhost:1527" "listen,resolve")
- JAVA础--利用java反射机制绕过编译时的类型检查和访问控制检查
- Java项目(前端vue后台java微服务)在线考试系统(java+vue+springboot+mysql+maven)
- JAVA单元测试框架-12-java代码重复执行失败的测试用例
- 详解Java中ThreadLocal类型
- Java SpringBoot 手记
- 【Java】整理关于java的String类,equals函数和比较操作符的区别
- Java基础语法:1.第一个java程序
- maven项目的java和resources等文件夹不在Java Resources的文件夹里,并且缺少Deployment...
- 基于Java(SSM)+Mysql实现SOSO 移动大厅业务办理(增删改查)【100010123】
- 检测网页地址有效性java代码
- 微软和Sun针对Java的世纪之战
- SpringBoot自定义注解,Springboot权限角色注解
- springBoot 自动装配,SpringBoot自动配置,SpringBoot自动加载
- Java返回结果封装,SpringBoot返回结果封装
- Java学习-089-springboot 通过 Spring Initializr 创建服务及IDEA导入后配置更新示例
- Java学习-068-Springboot 解决 maven 资源过滤导致的网页按钮图标显示异常( Failed to decode downloaded font )
- JAVA springboot启动报错:找不到或无法加载主类解决办法
- [开源框架推荐]Icepdf:纯java的pdf文档的提取和转换库
- 【蓝桥杯Java组】一学就会的小技巧(三):快速幂
- Java并发编程--总结
- 【JAVA】【NIO】10、Java NIO ServerSocketChannel
- Java 猜字母2014
- 解决Java使用response下载文件报错,并总结可能出错的原因: java.io.IOException: 你的主机中的软件中止了一个已建立的连接。
- nested exception is java.lang.NoClassDefFoundError: com/taotao/pojo/TbContentExample$Criteria] with