Spring boot使用JWT

1.pom文件引入依赖:

<!--jwt依赖-->
<dependency>
     <groupId>com.auth0</groupId>
     <artifactId>java-jwt</artifactId>
     <version>3.1.0</version>
</dependency>

2.创建JwtUtils工具类:

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class GatewayJwtUtil {
    /**
     * 加密算法中加的盐
     */
    private static final String SECRET = "9a96349";

    /**
     * 用户,发布人
     */
    private static String ISSUER = "sys_user";

    /**
     * 生成token
     * @param claims 传入参数
     * @return String
     */
    public String genToken(Map<String, String> claims){

        String token;
        //发布时间
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        // 生成JWT过期的时间
        long ttlMillis = nowMillis + 24L * 60L * 3600L * 1000L;
        Date expTime = new Date(ttlMillis);
        try {
            //使用HMAC256进行加密
            Algorithm algorithm = Algorithm.HMAC256(SECRET);

            //创建jwt,添加发行人,发布的时间点
            JWTCreator.Builder builder = JWT.create()
                    .withIssuer(ISSUER)
                    .withIssuedAt(expTime)
                    .withIssuedAt(now);

            //传入参数
            claims.forEach((key,value)-> {
                builder.withClaim(key, value);
            });

            //签名加密
            token = builder.sign(algorithm);
        } catch (IllegalArgumentException | UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return token;
    }

    /**
     * 解密jwt
     * @param token token
     * @return Map
     * @throws RuntimeException 运行时异常
     */
    public Map<String,String> verifyToken(String token) throws RuntimeException{
        Algorithm algorithm = null;
        try {
            //使用HMAC256进行加密
            algorithm = Algorithm.HMAC256(SECRET);
        } catch (IllegalArgumentException | UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        //解密
        JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
        DecodedJWT jwt =  verifier.verify(token);
        Map<String, Claim> map = jwt.getClaims();
        Map<String, String> resultMap = new HashMap<>();
        map.forEach((k,v) -> resultMap.put(k, v.asString()));
        return resultMap;
    }
 }

3.测试工具类:

{
		Map<String,String> map = new HashMap<>(16);
        map.put("name","张三");
        map.put("sex","男");
        String token = jwtUtil.genToken(map);
        System.out.println(token);

        map = jwtUtil.verifyToken(token);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
        }
}

运行截图:
在这里插入图片描述
打开 https://jwt.io/ 进行JWT验证。
在这里插入图片描述
对于JWT更为重要的是对JWT的理解,实战中使用还需要多多了解更多的知识

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值