spring boot java jwt,Spring boot中使用jwt(示例代码)

spring boot 使用 jwt

本文旨在介绍如何在spring boot中使用jwt,不会介绍什么是jwt。

一、导入依赖

1. spring-boot依赖

org.springframework.boot

spring-boot-starter-parent

2.2.6.RELEASE

org.springframework.boot

spring-boot-starter-web

org.projectlombok

lombok

true

org.springframework.boot

spring-boot-starter-test

test

org.junit.vintage

junit-vintage-engine

org.junit.jupiter

junit-jupiter-api

junit

junit

test

2. jwt 依赖

com.auth0

java-jwt

3.4.0

二、应用

创建一个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 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));

}

}

测试结果:

20200510210001233083.png

20200510210001403971.png

以上就是对jwt的基本操作,具体请看文档

三、参考文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值