使用RSA算法签名,生成jwt令牌,这里用spring-security-jwt库,也可以使用jjwt库。
只支持keystore为jks类型的证书。私钥加密,公钥验签。
1、生成jwt
public class CreateJwtTest { /*** * 创建令牌测试 */ @Test public void testCreateToken(){ //证书文件路径 String key_location="abc.jks"; //秘钥库密码 String key_password="abc"; //秘钥密码 String keypwd = "abc"; //秘钥别名 String alias = "abc"; //访问证书路径 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(); //定义Payload Map<String, Object> tokenMap = new HashMap<>(); tokenMap.put("id", "1"); tokenMap.put("name", "me"); tokenMap.put("roles", "ROLE_POWER,ROLE_USER"); //生成Jwt令牌 Jwt jwt = JwtHelper.encode(JSON.toJSONString(tokenMap), new RsaSigner(rsaPrivate)); //取出令牌 String encoded = jwt.getEncoded(); System.out.println(encoded); } }
2、取出令牌
public class ParseJwtTest { /*** * 校验令牌 */ @Test public void testParseToken(){ //令牌 String token = "略"; //公钥 String publickey = "略"; //校验Jwt并生成jwt对象 Jwt 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); } }