Java使用JWT

一、JWT简介

JWT(JSON WEB TOKEN)是一套开源的身份验证协议/解决方案。
了解,JWT,看阮一峰的博客:
http://www.ruanyifeng.com/blog/2018/07/json_web_token-tutorial.html

二、jwt java api

maven依赖:

<!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
		<dependency>
			<groupId>com.auth0</groupId>
			<artifactId>java-jwt</artifactId>
			<version>3.7.0</version>
		</dependency>

示例代码:

package jwt.jwt;

import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

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

public class JwtDemo {
	//JWT验证token的密钥
	private static final String JWT_SECRET = "your secret can't be exposed";
	
	public static void main(String[] args) {
		//签名算法,根据密钥,生成Algorithm实例,通常应用生命周期内都可以使用这个对象
		Algorithm algorithm = Algorithm.HMAC256(JWT_SECRET);
		
		//根据Algorithm生成token
		Builder tokenBuilder = JWT.create();
		
		//配置token的Header自定义部分
		Map<String, Object> headers = new HashMap<>();
		headers.put("myheader", "myheader");
		tokenBuilder.withHeader(headers);
		
		//配置token的PayLoad部分预定义字段
		tokenBuilder.withIssuer("iss")
			.withSubject("sub")
			.withAudience("viewer1", "viewer2")
			.withExpiresAt(new Date(System.currentTimeMillis() + 5000));
		
		//配置PayLoad部分自定义字段
		tokenBuilder.withClaim("name", "jack")
			.withArrayClaim("pets", new String[] {"cat", "dog", "bird"});
		
		//根据Alogrithm,签名后生成token
		String token = tokenBuilder.sign(algorithm);
		System.out.println("token : " + token);
		
		//解密token看下内容
		DecodedJWT decodedJWT = JWT.decode(token);
		System.out.println("header : " + decodeBase64Url(decodedJWT.getHeader()));
		System.out.println("payload : " + decodeBase64Url(decodedJWT.getPayload()));
		
		//构造JWTVerifier,用于验证token,这里说明,
		//签名及payload用来验证token,header的自定义字段则不用于验证
		JWTVerifier jwtVerifier = JWT.require(algorithm)
			.withIssuer("iss")
			.withAudience("viewer1", "viewer2")
			.acceptExpiresAt(System.currentTimeMillis() + 5000)
			.withSubject("sub")
			.withClaim("name", "jack") //可以尝试修改verifier,则下面的验证会抛异常
			.withArrayClaim("pets", new String[] {"cat", "dog", "bird"})
			.build();
		
		//使用Verifier执行验证
		DecodedJWT decodedJWT2 = jwtVerifier.verify(token);
		System.out.println("payload again: " + decodeBase64Url(decodedJWT2.getPayload()));
	}
	
	private static String decodeBase64Url(String base64Url) {
		return new String(Base64.getUrlDecoder().decode(base64Url));
	}
}

猜你喜欢

转载自blog.csdn.net/qq_21508059/article/details/88243294