使用RSA验证JWT令牌

迷你沙

我正在尝试验证jwt令牌并获取异常:线程“ main”中的异常java.lang.IllegalArgumentException:当前仅支持私钥数据

关于如何使用公共密钥验证jwt令牌的任何指针?

import org.springframework.security.jwt.JwtHelper;

 public  boolean verify(String jwtToken) {
            ResponseEntity<JwtKey> response = restTemplate.getForEntity(tokenKey, JwtKey.class);
            JwtKey jwtKey = response.getBody();
            Jwt decode = JwtHelper.decode(jwtToken);
            System.out.println(decode);
            System.out.println(decode.getClaims());
            JwtHelper.decodeAndVerify(jwtToken, new RsaVerifier(jwtKey.getValue()));

            return true;
        }
迷你沙

最后,我采用了以下解决方案。

import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.apache.commons.lang.StringUtils;

 public boolean verify(String jwtToken) {
        JWTKey jwtKey = restTemplateManager.getTokenPublicKey();
        try {
            JwtHelper.decodeAndVerify(jwtToken, new RsaVerifier(getRSAPublicKey(jwtKey.getValue())));
        } catch (Exception e) {
            logger.error("Error in verifying token{}", e);
            return false;
        }
        return true;
    }


 private RSAPublicKey getRSAPublicKey(String publicKey) {
        if( StringUtils.isBlank(publicKey)) return null;
        publicKey = sanitaize(publicKey);
        try {
            KeyFactory keyFactory = java.security.KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(java.util.Base64.getDecoder().decode(publicKey));
            return (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
            logger.error("Error forming RSA key {}", e);
            throw new GatewayException(e);
        }
    }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章