springboot token生成方式

本文介绍了一种使用JWT(JSON Web Tokens)进行用户认证的方法。详细展示了如何设置Token的有效期、构造JWT头部信息及载荷部分,并利用HS256算法进行签名。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
     * token秘钥 统一使用的秘钥
     */
    public static final String SECRET_UNIFORM = "XDD6897!&@#.,?";
    /**
     * token 过期时间: 3天
     */
    public static final int calendarField = Calendar.DATE;
    public static final int calendarInterval = 3;
	  Calendar nowTime = Calendar.getInstance();
        nowTime.add(calendarField, calendarInterval);
        Date expiresDate = nowTime.getTime();
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        String tokenKey = tokenType.getType() + userId.toString();
        
		String token = JWT.create().withHeader(map) // header
                    .withClaim("iss", "Service") // payload
                    .withClaim("aud", "APP")
                    .withClaim("userId", null == userId ? null : userId.toString())
                    .withClaim("type",tokenType.getType())
                    .withClaim("tokenKey",tokenKey)
                    .withArrayClaim("roles", roles)
                    .withIssuedAt(iatDate) // sign time
                    .withExpiresAt(expiresDate) // expire time
                    .sign(Algorithm.HMAC256(SECRET_UNIFORM)); //

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值