期待使用“ Nimbus JOSE + JWT”库开发具有RSA加密功能的JWT(Json Web令牌)。谁能尽快提供示例代码给我?

我想使用以下Maven依赖项:

<dependency>
    <groupId>com.nimbusds</groupId>
    <artifactId>nimbus-jose-jwt</artifactId>
    <version>3.10</version>
</dependency>


注意:请始终使用Maven Central存储库中的最新版本。

最佳答案

如果您使用的是最新版本的“ Nimbus Jose JWT” 4.23,则API中会有一些小的更改。

<dependency>
    <groupId>com.nimbusds</groupId>
    <artifactId>nimbus-jose-jwt</artifactId>
    <version>4.23</version>
</dependency>


我已显示以下代码供参考:

public class JwtJoseExample {
    public static void main(String[] args) {
        KeyPairGenerator keyPairGenerator;
        try {
            keyPairGenerator = KeyPairGenerator.getInstance("RSA");

            keyPairGenerator.initialize(1024);

            // generate the key pair
            KeyPair keyPair = keyPairGenerator.genKeyPair();

            // create KeyFactory and RSA Keys Specs
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKeySpec publicKeySpec = keyFactory.getKeySpec(keyPair.getPublic(), RSAPublicKeySpec.class);
            RSAPrivateKeySpec privateKeySpec = keyFactory.getKeySpec(keyPair.getPrivate(), RSAPrivateKeySpec.class);

            // generate (and retrieve) RSA Keys from the KeyFactory using Keys Specs
            RSAPublicKey publicRsaKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
            RSAPrivateKey privateRsaKey  = (RSAPrivateKey) keyFactory.generatePrivate(privateKeySpec);

            JWTClaimsSet.Builder claimsSet = new JWTClaimsSet.Builder();
            claimsSet.issuer("https://my-auth-server.com");
            claimsSet.subject("John Kerr");
            claimsSet.audience(getAudience());
            claimsSet.expirationTime(new Date(new Date().getTime() + 1000*60*10));
            claimsSet.notBeforeTime(new Date());
            claimsSet.jwtID(UUID.randomUUID().toString());

            System.out.println("--------------------------");
            System.out.println("Claim Set : \n"+claimsSet.build());

            // create the JWT header and specify:
            //  RSA-OAEP as the encryption algorithm
            //  128-bit AES/GCM as the encryption method
            JWEHeader header = new JWEHeader(JWEAlgorithm.RSA_OAEP, EncryptionMethod.A128GCM);

            // create the EncryptedJWT object
            EncryptedJWT jwt = new EncryptedJWT(header, claimsSet.build());

            // create an RSA encrypter with the specified public RSA key
            RSAEncrypter encrypter = new RSAEncrypter(publicRsaKey);

            // do the actual encryption
            jwt.encrypt(encrypter);

            // serialize to JWT compact form
            String jwtString = jwt.serialize();
            System.out.println("\nJwt Compact Form : "+jwtString);

            // in order to read back the data from the token using your private RSA key:
            // parse the JWT text string using EncryptedJWT object
            jwt = EncryptedJWT.parse(jwtString);

            // create a decrypter with the specified private RSA key
            RSADecrypter decrypter = new RSADecrypter(privateRsaKey);

            // do the decryption
            jwt.decrypt(decrypter);

            // print out the claims

            System.out.println("===========================================================");
            System.out.println("Issuer: [ " + jwt.getJWTClaimsSet().getIssuer() + "]");
            System.out.println("Subject: [" + jwt.getJWTClaimsSet().getSubject()+ "]");
            System.out.println("Audience size: [" + jwt.getJWTClaimsSet().getAudience().size()+ "]");
            System.out.println("Expiration Time: [" + jwt.getJWTClaimsSet().getExpirationTime()+ "]");
            System.out.println("Not Before Time: [" + jwt.getJWTClaimsSet().getNotBeforeTime()+ "]");
            System.out.println("Issue At: [" + jwt.getJWTClaimsSet().getIssueTime()+ "]");
            System.out.println("JWT ID: [" + jwt.getJWTClaimsSet().getJWTID()+ "]");
            System.out.println("===========================================================");

        } catch (NoSuchAlgorithmException | InvalidKeySpecException | JOSEException | ParseException e) {
            System.out.println(e.getMessage());
        }
    }

    private static List<String> getAudience(){
        List<String> audience = new ArrayList<>();
        audience.add("https://my-web-app.com");
        audience.add("https://your-web-app.com");
        return audience;
    }
}


   输出为:

声明集:

{"sub":"John Kerr","aud":["https:\/\/my-web-app.com","https:\/\/your-web-app.com"],"nbf":1471116052,"iss":"https:\/\/my-auth-server.com","exp":1471116652,"jti":"8769fc6d-b69f-45e3-b1a5-52695c23675e"}


Jwt紧凑型:

eyJlbmMiOiJBMTI4R0NNIiwiYWxnIjoiUlNBLU9BRVAifQ.f2ZZyMaJi03RqunyWsLvIr7tNX1KvTRUcpN9qsBHvbXIouZCyepQMsbI1v88GHuLIV3f6SviCDyICp7kZCj_9q-yIi_dIuroADWQ-P_UnqNPRXQ1yEwbmrLUK80lBtKyc3Z6g_3Db_HLtD6QPEq-zUAh3wJ7uSPxhql2oc9otGc.Xbyrf4iWM0shNp4S.TCKoJGAEQ4rpJJk2qZP11awxTEWTg-r5VpppGgZNhiHCBhnGnyR2sb86O7ISc3j-i4OYp7Xl2vThzztD1ojy_IKPYQkg_iACuo6yjzdopQQT143vjYuFLfFhQFfjfCoO6iibTqK7vmqfF0bUWD6Nj-4MwjlW6dFV7mNQEN50dkiMrFMZkmiVKZRa50jOK1NcoWYiKSrCOQduJYibJfF6jSQARX9MsX5tib-3BXSsKtPLNrQ6mFfvDzzruBuO4gKWLE3PQPUfIQ.gXt5KcpxEbfYLP854GvcQw
===========================================================
Issuer: [ https://my-auth-server.com]
Subject: [John Kerr]
Audience size: [2]
Expiration Time: [Sun Aug 14 01:00:52 IST 2016]
Not Before Time: [Sun Aug 14 00:50:52 IST 2016]
Issue At: [null]
JWT ID: [8769fc6d-b69f-45e3-b1a5-52695c23675e]
===========================================================

08-04 21:15
查看更多