“必填字段丢失”来自apigee api的响应

b4qexyjb  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(330)

我正在使用android中的nimbus jose jwt库生成加密jwt(jwe),并将其发送到apigee api的主体中。
我使用以下代码生成加密jwt:

public class EncryptedJWTGenerator {
    String jweString;
    Map<String, Object> map = new HashMap<>();

    @RequiresApi(api = Build.VERSION_CODES.O)
    public EncryptedJWTGenerator() throws NoSuchAlgorithmException, JOSEException, InvalidKeySpecException {

        String publicKey = <my_public_key>;

        try {
            // create Gson instance
            Gson gson = new Gson();

            URL url = getClass().getResource("Payload.json"); //JSON file having the Payload

            // create a reader
            Reader reader = Files.newBufferedReader(Paths.get(url.toURI().getPath()));

            // convert JSON file to map
            map = gson.fromJson(reader, Map.class);

            // print map entries
            for (Map.Entry<?, ?> entry : map.entrySet()) {
                System.out.println(entry.getKey() + "=" + entry.getValue());
            }

            // close reader
            reader.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        JWEAlgorithm alg = JWEAlgorithm.RSA_OAEP_256;
        EncryptionMethod enc = EncryptionMethod.A256GCM;

        byte[] publicBytes = Base64.decodeBase64(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey pubKey = keyFactory.generatePublic(keySpec);

        // Generate the preset Content Encryption (CEK) key
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(EncryptionMethod.A256GCM.cekBitLength());

        SecretKey cek = keyGenerator.generateKey();

        JOSEObjectType joseObjectType = new JOSEObjectType("JWT");
        JWEHeader jweHeader = new JWEHeader(alg, enc, joseObjectType, null, null, null, null, null, null, null, null, null, null,
                null, null, null, null, 0, null, null, null, null);

        // Encrypt the JWE with the RSA public key + specified AES CEK
        JWEObject jweObject = new JWEObject(new JWEHeader(jweHeader), new Payload(map));

        jweObject.encrypt(new RSAEncrypter((RSAPublicKey) pubKey, cek));

        jweString = jweObject.serialize();
    }
}

但是当我在api主体中使用这个jwe时,我得到以下响应:

{
    "Code": 0,
    "Response": {},
    "Message": "Mandatory Fields are missing"
}

但是当我使用这个工具时-> https://dinochiesa.github.io/jwt/ 要生成jwe并将其与apigee api一起使用,它工作得很好。
我在jwe一代的代码中遗漏了什么吗?

0lvr5msh

0lvr5msh1#

解决方法是将我的json作为字符串传递给有效负载,而不是从文件中读取并转换为Map并将其传递给有效负载。
取代 JWEObject jweObject = new JWEObject(new JWEHeader(jweHeader), new Payload(map)); 与:

JWEObject jweObject = new JWEObject(new JWEHeader(jweHeader), new Payload(<my_json_string>));

相关问题