Spring boot中使用jwt

2021-01-24 16:15

阅读:431

标签:algo   基本   tps   hashmap   project   engine   tcl   create   version   

spring boot 使用 jwt

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

一、导入依赖

1. spring-boot依赖


org.springframework.boot
	spring-boot-starter-parent
	2.2.6.RELEASEorg.springframework.boot
        spring-boot-starter-web
    org.projectlombok
        lombok
        trueorg.springframework.boot
        spring-boot-starter-test
        testorg.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));
    }
}

测试结果:

技术图片

技术图片

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

三、参考文档

java-jwt : https://github.com/auth0/java-jwt

Spring boot中使用jwt

标签:algo   基本   tps   hashmap   project   engine   tcl   create   version   

原文地址:https://www.cnblogs.com/ycwiacb/p/12864883.html


评论


亲,登录后才可以留言!