一、 基于私钥生成jwt令牌
步骤:
导入认证服务
-
将shangcheng_user_auth工程导入到项目中去,如下图
-
启动eureka,再启动认证服务
3) 认证服务中创建测试类
public class CreateJwtTest {
/**** 创建令牌测试*/@Testpublic void testCreateToken(){//证书文件路径String key_location="shangcheng.jks";//秘钥库密码String key_password="shangcheng";//秘钥密码String keypwd = "shangcheng";//秘钥别名String alias = "shangcheng";
//访问证书路径ClassPathResource resource = new ClassPathResource(key_location);
//创建秘钥工厂KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(resource,key_password.toCharArray());
//读取秘钥对(公钥、私钥)KeyPair keyPair = keyStoreKeyFactory.getKeyPair(alias,keypwd.toCharArray());
//获取私钥RSAPrivateKey rsaPrivate = (RSAPrivateKey) keyPair.getPrivate();
//定义PayloadMap<String, Object> tokenMap = new HashMap<>();tokenMap.put("id", "1");tokenMap.put("name", "itheima");tokenMap.put("roles", "ROLE_VIP,ROLE_USER");
//生成Jwt令牌Jwt jwt = JwtHelper.encode(JSON.toJSONString(tokenMap), new RsaSigner(rsaPrivate));
//取出令牌String encoded = jwt.getEncoded();System.out.println(encoded);}
}
二、 基于公钥解析jwt令牌
上面创建令牌后,我们可以对JWT令牌进行解析,这里解析需要用到公钥,我们可以将之前生成的公钥public.key拷贝出来用字符串变量token存储,然后通过公钥解密。
在shangcheng-user-oauth创建测试类com.shangcheng.token.ParseJwtTest实现解析校验令牌数据,代码如下:
public class ParseJwtTest {
/**** 校验令牌*/@Testpublic void testParseToken(){//令牌String token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlcyI6IlJPTEVfVklQLFJPTEVfVVNFUiIsIm5hbWUiOiJpdGhlaW1hIiwiaWQiOiIxIn0.IR9Qu9ZqYZ2gU2qgAziyT38UhEeL4Oi69ko-dzC_P9-Vjz40hwZDqxl8wZ-W2WAw1eWGIHV1EYDjg0-eilogJZ5UikyWw1bewXCpvlM-ZRtYQQqHFTlfDiVcFetyTayaskwa-x_BVS4pTWAskiaIKbKR4KcME2E5o1rEek-3YPkqAiZ6WP1UOmpaCJDaaFSdninqG0gzSCuGvLuG40x0Ngpfk7mPOecsIi5cbJElpdYUsCr9oXc53ROyfvYpHjzV7c2D5eIZu3leUPXRvvVAPJFEcSBiisxUSEeiGpmuQhaFZd1g-yJ1WQrixFvehMeLX2XU6W1nlL5ARTpQf_Jjiw";
//公钥String publickey = "-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvFsEiaLvij9C1Mz+oyAmt47whAaRkRu/8kePM+X8760UGU0RMwGti6Z9y3LQ0RvK6I0brXmbGB/RsN38PVnhcP8ZfxGUH26kX0RK+tlrxcrG+HkPYOH4XPAL8Q1lu1n9x3tLcIPxq8ZZtuIyKYEmoLKyMsvTviG5flTpDprT25unWgE4md1kthRWXOnfWHATVY7Y/r4obiOL1mS5bEa/iNKotQNnvIAKtjBM4RlIDWMa6dmz+lHtLtqDD2LF1qwoiSIHI75LQZ/CNYaHCfZSxtOydpNKq8eb1/PGiLNolD4La2zf0/1dlcr5mkesV570NxRmU1tFm8Zd3MZlZmyv9QIDAQAB-----END PUBLIC KEY-----";
//校验JwtJwt jwt = JwtHelper.decodeAndVerify(token, new RsaVerifier(publickey));
//获取Jwt原始内容String claims = jwt.getClaims();System.out.println(claims);//jwt令牌String encoded = jwt.getEncoded();System.out.println(encoded);}
}
注:
对于令牌的解析,公钥和私钥是成对出现的,用正确的公钥去解析相对应的以私钥作为签名的JWT令牌,否则的话无法进行解析。