HappyHeng 2020-05-10
spring boot
中使用jwt
,不会介绍什么是jwt
。<!--父依赖--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.6.RELEASE</version> <relativePath/> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> <exclusion> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> </dependencies>
<dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.4.0</version> </dependency>
创建一个JwtUtil文件
package cn.edu.swpu.news.util; import cn.edu.swpu.news.entity.User; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import lombok.extern.slf4j.Slf4j; import java.time.*; import java.util.HashMap; import java.util.Map; /** * jwt工具类 * @author ycwiacb 2020/5/2 */ @Slf4j public class JwtUtil { //这里填写你自己自定义的SECRET private static final String SECRET = "ycwiacb-secret"; /**生成token*/ public static String sign(User user) { Algorithm algorithm = Algorithm.HMAC256(SECRET); Map<String, Object> map = new HashMap<>(16); map.put("alg", "HS256"); map.put("typ", "JWT"); return JWT.create().withHeader(map) .withClaim("userId", user.getId()) .withClaim("username", user.getUsername()) .withIssuer("ycwiacb") .withIssuedAt(DateUtil.localDateTimeToDate(LocalDateTime.now())) .withExpiresAt(DateUtil.localDateTimeToDate(LocalDateTime.now().plusMinutes(30))) .sign(algorithm); } /**验证token并返回id*/ public static Long verify(String token) { long userId = 0L; try { Algorithm algorithm = Algorithm.HMAC256(SECRET); JWTVerifier jwtVerifier = JWT.require(algorithm) .withIssuer("ycwiacb") .build(); DecodedJWT decodedjwt = jwtVerifier.verify(token); userId = decodedjwt.getClaim("userId").asLong(); } catch (JWTVerificationException e) { log.error("解析token失败, exception = {}", e.toString()); } return userId; } }
注意:这里使用的是decodedjwt.getClaim("userId").asLong(); 这里是asLong(),对应的有asString(),而非toString()。
附上DateUtil文件
package cn.edu.swpu.news.util; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; /** * @author ycwiacb 2020/5/5 */ public class DateUtil { /** *将LocalDateTime 时间类转化为Date * @return Date */ public static Date localDateTimeToDate(LocalDateTime dateTime) { return Date.from(dateTime.atZone(ZoneId.of("Asia/Shanghai")).toInstant()); } }
测试,JwtUtilTest.java
package cn.edu.swpu.news.util; import cn.edu.swpu.news.entity.User; import org.junit.Test; /** * @author ycwiacb 2020/5/10 */ public class JwtUtilTest { @Test public void sign() { User user = new User(); user.setId(1L); user.setUsername("testUserName"); System.out.println("测试jwt:token = " + JwtUtil.sign(user)); } @Test public void verify() { String token = "你生成的token"; System.out.println("解析token:userId=" + JwtUtil.verify(token)); } }
测试结果:
以上就是对jwt的基本操作,具体请看文档
java-jwt : https://github.com/auth0/java-jwt