使用JWT(java JWT)验证签名

使用JWT(java JWT)验证签名,java,jwt,Java,Jwt,我必须使用java jwt库验证签名,我有令牌和公钥,公钥从ssh rsa AA开始。。。。。。。。。。。。。。。 我必须使用RSA256算法,当我检查github时,我发现如下 Algorithm algorithm = Algorithm.RSA256(publicKey, privateKey); JWTVerifier verifier = JWT.require(algorithm) .withIssuer("auth0") .build(); //Reusable v

我必须使用java jwt库验证签名,我有令牌和公钥,公钥从ssh rsa AA开始。。。。。。。。。。。。。。。 我必须使用RSA256算法,当我检查github时,我发现如下

Algorithm algorithm = Algorithm.RSA256(publicKey, privateKey);
JWTVerifier verifier = JWT.require(algorithm)
    .withIssuer("auth0")
    .build(); //Reusable verifier instance
DecodedJWT jwt = verifier.verify(token);

但是我的公钥是字符串形式的,我没有私钥。。请建议我如何验证签名。

如果您是令牌生成器,您必须拥有用于生成令牌的私钥

除非您拥有私钥,否则无法验证令牌

如果您在客户端使用令牌,则不需要验证它

如果您只想在写入功能之前验证令牌,可以转到:

如果你能做到这一点,这会很有帮助:

如果有人在服务器上请求资源,您可以执行以下操作:

try {

    Jwts.parser().setSigningKey(key).parseClaimsJws(compactJws);

    //OK, we can trust this JWT

} catch (SignatureException e) {

    //don't trust the JWT!
}

我希望这有帮助…

这似乎是一个缺陷/限制,您似乎需要公钥和私钥来验证签名。使用RSA256算法验证JWT时,不需要私钥

这个处理JWT:的替代java库没有相同的限制,因此我建议使用它

Jwts.parser()    
  .setSigningKey(publicKey) // <---- publicKey, not privateKey  
  .parseClaimsJws(jwsString);
Jwts.parser()

.setSigningKey(publicKey)/使用非对称密钥加密时,我们需要私钥来创建签名,并需要公钥来验证。 来回答你的问题

1。私密信息不存在

很好,您不需要私钥来验证签名。关于您正在使用的库,它的变量args。这意味着您可以根据签名/验证通过一个。下面是只使用公钥的java方法

    public boolean verifyToken(String token,RSAPublicKey publicKey){
    try {
        Algorithm algorithm = Algorithm.RSA256(publicKey, null);
        JWTVerifier verifier = JWT.require(algorithm)
                //more validations if needed
                .build();
        verifier.verify(token);
        return true;
    } catch (Exception e){
        System.out.println("Exception in verifying "+e.toString());
        return false;
    }
}
2。公钥是字符串格式,而不是java公钥格式。

您需要一种机制将公钥字符串文件转换为Java公钥格式。下面是我可以建议的一种方法

    public static RSAPublicKey getPublicKeyFromString(String key) throws 
    IOException, GeneralSecurityException {

    String publicKeyPEM = key;

    /**replace headers and footers of cert, if RSA PUBLIC KEY in your case, change accordingly*/
    publicKeyPEM = publicKeyPEM.replace("-----BEGIN PUBLIC KEY-----\n", "");
    publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");

    byte[] encoded = Base64.decodeBase64(publicKeyPEM);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(new X509EncodedKeySpec(encoded));

    return pubKey;
    }

这个回答是正确的。如果需要验证JWT客户端,则说明使用了错误的技术。JWT包含后端状态,但请求客户端保留该状态。这使得后端无状态,任何虚拟后端服务器都可以处理任何请求,因为后端状态包含在每个请求中(在JWT中)。如果您需要来自后端的数据,并且需要验证并确保特定后端提供该数据,https应该足够了。@AndreasLundgren谢谢。基于公钥/私钥的签名算法的全部要点不就是任何人都可以在没有私钥的情况下验证签名吗?!不明白为什么没有私钥无法验证令牌。这可以在node.js lib中完成,似乎是OP中引用的特定java lib实现的缺陷/限制。来源:“使用RSA或ECDSA算法时,您只需对JWTs进行签名,就可以通过传递空值来避免指定公钥。当您只需要验证JWTs时,也可以使用私钥执行相同的操作。”