安全(7) : JWT鉴权

该文章展示了如何在Java中使用com.auth0.jwt库生成和验证JSONWebTokens(JWT)。代码包括创建JWT,设置头信息,添加声明(如用户名和密码),并设定过期时间,然后使用相同的密钥进行解码和验证。
摘要由CSDN通过智能技术生成

参考 : JWT鉴权_chiamp的博客-CSDN博客


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: liyue
 * @Date: 2023/04/03/11:34
 * @Description:
 */
public class JwtTest {

    private static final String secret = "sofhjsje8f7he3$#3%#jesjfsjf";

    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) throws ParseException {
        String token = generateCode("2023-04-03 11:50:00");
        System.out.println(token);
        analysis(token);
    }

    public static String generateCode(String expireTime) throws ParseException {
        Map<String, Object> map = new HashMap<>();
        map.put("typ", "jwt");
        map.put("alg", "HS256");
        String token = JWT.create()
                .withHeader(map)
                .withClaim("username", "root")
                .withClaim("password", "123456")
                .withExpiresAt(simpleDateFormat.parse(expireTime))
                .sign(Algorithm.HMAC256(secret));  // 签名secret
        return token;
    }

    public static void analysis(String token) {
        // 创建解析对象,使用的算法和secret要与创建token时保持一致
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
        // 解析指定的token
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        // 获取解析后的token中的payload信息
        Date expiresAt = decodedJWT.getExpiresAt();
        System.out.println("username:"+decodedJWT.getClaim("username").toString());
        System.out.println("password:"+decodedJWT.getClaim("password").toString());
        System.out.println("过期时间:"+simpleDateFormat.format(expiresAt));
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值