JWT生成与验证

JsonWebToken好处与原理就不记录了,最近经常使用这个token,写了验证方法,以至于好奇如何自己生成。就写了Demo

demo完整代码https://download.csdn.net/download/A564492203/12040005

重要代码如下

引入

<dependency>
  <groupId>com.auth0</groupId>
  <artifactId>java-jwt</artifactId>
  <version>3.2.0</version>
</dependency>
        
<dependency>
  <groupId>io.jsonwebtoken</groupId>
  <artifactId>jjwt</artifactId>
  <version>0.7.0</version>
</dependency>

 工具类

package com.libinbin.util;

import java.util.Date; 

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.util.encoders.Base64;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;

public class JwtUtils {
	
	private static String secret = "password"; 

        //生成jwt
	public static String createJWTString(String id,String sub,long millis) {
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);
		long expMillis = nowMillis + millis;
		Date expDate = new Date(expMillis);
		SecretKey secretKey = getKey();
		JwtBuilder builder = Jwts.builder()
				.setId(id)
				.setSubject(sub)
				.setIssuer("name")
				.setIssuedAt(now)
				.signWith(signatureAlgorithm, secretKey)
				.setExpiration(expDate);
		return builder.compact();
	}
	
        //验证jwt
	public static CheckResult checkJWT(String jwtString) {
		CheckResult checkResult = new CheckResult();
		Claims claims = null;
		try {
			claims = changeJWT(jwtString);
			checkResult.setSuccess(true);
			checkResult.setClaims(claims);
		}catch (ExpiredJwtException e) {//过期
			checkResult.setSuccess(false);
			checkResult.setErrorCode(-100);
		}catch (SignatureException e) {//篡改
			checkResult.setSuccess(false);
			checkResult.setErrorCode(-200);
		}catch (Exception e) {//其他
			checkResult.setSuccess(false);
			checkResult.setErrorCode(-200);
		}
		return checkResult;
	}
	
	public static SecretKey getKey() {
		byte[] decodeKey = Base64.decode(secret);
		SecretKey key = new SecretKeySpec(decodeKey, 0, decodeKey.length, "AES");
		return key;
	}
	
	public static Claims changeJWT(String jwtString) throws Exception{
		SecretKey secretKey = getKey();
		return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwtString).getBody();
	}
	
	public static void main(String[] args) {
		String jwtStr = createJWTString("1", "10000", 1000*60*60);
		System.out.println(jwtStr);
		CheckResult ch = checkJWT(jwtStr);
		System.out.println(ch.toString());
	}
	
}

返回结果类

package com.libinbin.util;

import io.jsonwebtoken.Claims;
import lombok.Data;

@Data
public class CheckResult {
	private Boolean success;
	private Claims claims;
	private Integer errorCode;
}

猜你喜欢

转载自blog.csdn.net/A564492203/article/details/103610058