Java 生成token

        <dependency>
            <groupId>org.bitbucket.b_c</groupId>
            <artifactId>jose4j</artifactId>
            <version>0.6.4</version>
        </dependency>
package com.buptnu.util;

public class UserToken {

	private String username;
	
	public UserToken() {
		
	}
	
	public UserToken(String username) {
		this.username = username;
	}
	
	public String getUsername() {
		return username;
	}
	
	public void setUsername(String username) {
		this.username = username;
	}
	
}

package com.buptnu.util;

import java.security.Key;

import org.jose4j.jws.AlgorithmIdentifiers;
import org.jose4j.jws.JsonWebSignature;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.consumer.JwtConsumer;
import org.jose4j.jwt.consumer.JwtConsumerBuilder;
import org.jose4j.keys.HmacKey;

public class TokenUtil {
	
	/**
	 * 过期时间:1分钟
	 */
	private static final int JWT_EXPIRE = 1;
	
	/**
	 * 密钥
	 */
	private static final String JWT_PRIVATE_KEY = "KRMEftu3JTRnlaFoRjnEcg==";
	
	/**
     * 生成token
     * @param userToken
     * @param expire
     * @return
     * @throws Exception
     */
    public static String generateToken(UserToken userToken) throws Exception {
        JwtClaims claims = new JwtClaims();
        claims.setSubject(userToken.getUsername());
        claims.setExpirationTimeMinutesInTheFuture(JWT_EXPIRE);

        Key key = new HmacKey(JWT_PRIVATE_KEY.getBytes("UTF-8"));

        JsonWebSignature jws = new JsonWebSignature();
        jws.setPayload(claims.toJson());
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
        jws.setKey(key);
        jws.setDoKeyValidation(false); // relaxes the key length requirement

        //签名
        String token = jws.getCompactSerialization();
        return token;
    }

    /**
     * 解析token
     * @param token
     * @return
     * @throws Exception
     */
    public static UserToken getInfoFromToken(String token) throws Exception {

        if (token == null) {
            return null;
        }

        Key key = new HmacKey(JWT_PRIVATE_KEY.getBytes("UTF-8"));

        JwtConsumer jwtConsumer = new JwtConsumerBuilder()
                .setRequireExpirationTime()
                .setAllowedClockSkewInSeconds(30)
                .setRequireSubject()
                .setVerificationKey(key)
                .setRelaxVerificationKeyValidation() // relaxes key length requirement
                .build();
        
        JwtClaims processedClaims = jwtConsumer.processToClaims(token);
        
        return new UserToken(processedClaims.getSubject());
    }
    
    public static void main(String[] args) throws Exception {
    	UserToken userToken = new UserToken("宇文泰");
    	String token = generateToken(userToken);
    	System.out.println("token是:" + token);
    	Thread.sleep(30000);// 30秒后读取
    	userToken = getInfoFromToken(token);
    	if (userToken != null) {
    		System.out.println("获取到名称:" + userToken.getUsername() + "。");
    	}
    	Thread.sleep(35000);// 35秒后读取,因为设置了允许偏差时间 setAllowedClockSkewInSeconds,所以不会过期
    	userToken = getInfoFromToken(token);
    	if (userToken != null) {
    		System.out.println("获取到名称:" + userToken.getUsername() + "。");
    	}
    	Thread.sleep(30000);// 30秒后读取
    	try {
    		getInfoFromToken(token);
    	} catch (Exception e) {
    		System.out.println("已过期,没有获取到名称!");
    		e.printStackTrace();
    	}
    }

}

token是:eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiLlrofmlofms7AiLCJleHAiOjE3MzU4MjA1MjB9.gY_enml8dCPKk7fyYUW2vteRo4IzQtMXNP-kdALmA6U
获取到名称:宇文泰。
获取到名称:宇文泰。
已过期,没有获取到名称!
org.jose4j.jwt.consumer.InvalidJwtException: JWT (claims->{"sub":"宇文泰","exp":1735820520}) rejected due to invalid claims. Additional details: [[1] The JWT is no longer valid - the evaluation time NumericDate{1735820556 -> 2025-1-2 下午08时22分36秒} is on or after the Expiration Time (exp=NumericDate{1735820520 -> 2025-1-2 下午08时22分00秒}) claim value (even when providing 30 seconds of leeway to account for clock skew).]
	at org.jose4j.jwt.consumer.JwtConsumer.validate(JwtConsumer.java:466)
	at org.jose4j.jwt.consumer.JwtConsumer.processContext(JwtConsumer.java:311)
	at org.jose4j.jwt.consumer.JwtConsumer.process(JwtConsumer.java:433)
	at org.jose4j.jwt.consumer.JwtConsumer.processToClaims(JwtConsumer.java:171)
	at com.buptnu.util.TokenUtil.getInfoFromToken(TokenUtil.java:71)
	at com.buptnu.util.TokenUtil.main(TokenUtil.java:92)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值