授权与认证之jwt(一)创建Jwt工具类

发布于:2025-03-03 ⋅ 阅读:(14) ⋅ 点赞:(0)

JWT的Token要经过加密才能返回给客户端,包括客户端上传的Tokn,后端项目需要验证核
实。于是我们需要一个WT工具类,用来加密Token和验证Token的有效性。

一、导入依赖

        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.10.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.11</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.13</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

二、定义密钥和过期时间

在application文件中加入,建议大家把密钥和过期时间定义到Spring Boot配置文件中,然后再值注入到javaBean中,这样维护起来比较方便。

emos:
  jwt:
    #密钥
    secret: abc123456
    #令牌过期时间(天)
    expire: 5
    #令牌缓存时间(天)
    cache-expire: 10

三、创建jwt工具类

@Component
@Slf4j
public class JwtUtil {

    @Value("${emos.jwt.secret}")  //读取的就是application文件中的数值
    private String secret;

    @Value("${emos.jwt.expire}")
    private int expire;

    //创建令牌
    private String createToken(int userId) {
        //根据expire算下过期时间在什么时候
        DateTime date = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, 5);

        //生成密钥
        Algorithm algorithm= Algorithm.HMAC256(secret);

        //创建内部类绑定userid,密钥和过期时间
        JWTCreator.Builder builder= JWT.create();

        builder.withClaim("userId", userId);
        builder.withExpiresAt(date);

        //生成的令牌
        String token = builder.sign(algorithm);
        return token;
    }

    //从令牌对象反向获取userid
    public int getUserId(String token) {
        DecodedJWT jwt = JWT.decode(token);

        Integer userId = jwt.getClaim("userId").asInt();
        return userId;
    }

    //验证令牌有效性
    public void verifyToken(String token) {
        //验证令牌内容有效性 创建算法对象
        Algorithm algorithm = Algorithm.HMAC256(token);

        //创建验证对象
        JWTVerifier build = JWT.require(algorithm).build();
        //验证token是否有问题
        build.verify(token);
    }
}