【问题标题】:JWT becomes invalid after restarting the server重启服务器后JWT失效
【发布时间】:2016-02-28 02:08:23
【问题描述】:

我正在生成一个公钥/私钥对,我将使用 jose4j 对 JWT 进行数字签名。它也可以很好地创建和验证令牌。但是一旦我重新启动服务器,之前发布的令牌就会失效。 我觉得每次我重新启动服务器时,它都会创建新密钥。这就是我在构造函数中生成密钥的方式:

    rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);
    // Give the JWK a Key ID (kid), which is just the polite thing to do
    rsaJsonWebKey.setKeyId("secretKey");

当我们尝试创建新的类实例时也会发生这种情况。它说令牌无效。

任何帮助将不胜感激。谢谢..

【问题讨论】:

    标签: java encryption jwt jose4j


    【解决方案1】:

    RsaJwkGenerator.generateJwk(...) 的每次调用都会生成一个新的公钥/私钥对。使用私钥签名的 JWT 上的签名只能使用相应的公钥进行验证(这是安全性的重要组成部分)。底线是需要为给定的上下文使用适当的密钥,这表明在您的应用程序中访问密钥的不同方式。

    因此,对于需要相同键的某个类的不同实例,键的某种单例可能是合适的。

    为了在应用程序重新启动后继续存在,密钥需要以某种方式持久化和加载。使用 java 的 Keystore 是您可以做到这一点的一种方法。或者整个 JWK 的 JSON 可以使用 rsaJsonWebKey.toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE) 作为字符串访问并保存在某处。不过,您确实需要小心使用私钥,因此请将其保存在安全的地方和/或也许您可以使用 JWE 对整个内容进行加密 - 此处显示了一些使用基于密码的加密的小代码:

        String jwkjson = rsaJsonWebKey.toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE);
        JsonWebEncryption encryptingJwe = new JsonWebEncryption();
        encryptingJwe.setAlgorithmHeaderValue(KeyManagementAlgorithmIdentifiers.PBES2_HS256_A128KW);
        encryptingJwe.setEncryptionMethodHeaderParameter(ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256);
        encryptingJwe.setKey(new PbkdfKey("some decent passphrase/password here"));
        encryptingJwe.setPayload(jwkjson);
        String jweEncryptedJwk = encryptingJwe.getCompactSerialization();
    
        // save  jweEncryptedJwk somewhere  and load it on application start 
    
        JsonWebEncryption decryptingJwe = new JsonWebEncryption();
        decryptingJwe.setCompactSerialization(jweEncryptedJwk);
        encryptingJwe.setKey(new PbkdfKey("some decent passphrase/password here"));
        String payload = encryptingJwe.getPayload();
        PublicJsonWebKey publicJsonWebKey = PublicJsonWebKey.Factory.newPublicJwk(payload);
        // share the public part with whomever/whatever needs to verify the signatures 
        System.out.println(publicJsonWebKey.toJson(JsonWebKey.OutputControlLevel.PUBLIC_ONLY));
    

    【讨论】:

    • 谢谢@brian。我会尝试您建议的方法并让您知道反馈。
    猜你喜欢
    • 2016-10-23
    • 2014-04-23
    • 1970-01-01
    • 2013-11-26
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    相关资源
    最近更新 更多