使用 Java 获取 Azure KeyVault 机密

Fetch Azure KeyVault Secret using Java

我在使用 Java

从 azure keyvault 检索机密时遇到一个问题

我使用了以下依赖项, azure-security-keyvault-secrets-4.3.6.jar azure-identity-1.4.2.jar azure-core-1.12.0.jar

还有我的代码,

String keyVaultUri = "https://keyvaultName.vault.azure.net";
SecretClient secretClient = new SecretClientBuilder()
    .vaultUrl(keyVaultUri)
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildClient();
    
KeyVaultSecret retrievedSecret = secretClient.getSecret("azureTableConnectionString");
System.out.println(retrievedSecret.getValue());

当我 运行 以上代码时,出现以下错误

Exception in thread "main" java.lang.NoClassDefFoundError: org/reactivestreams/Publisher
    at com.azure.core.http.policy.RetryPolicy.<init>(RetryPolicy.java:73)
    at com.azure.core.http.policy.RetryPolicy.<init>(RetryPolicy.java:37)
    at com.azure.security.keyvault.secrets.SecretClientBuilder.<init>(SecretClientBuilder.java:123)
    at sage50ukv26.test_0_1.test.tJava_1Process(test.java:892)
    at sage50ukv26.test_0_1.test.tLibraryLoad_3Process(test.java:814)
    at sage50ukv26.test_0_1.test.tLibraryLoad_2Process(test.java:651)
    at sage50ukv26.test_0_1.test.tLibraryLoad_1Process(test.java:499)
    at sage50ukv26.test_0_1.test.runJobInTOS(test.java:1434)
    at sage50ukv26.test_0_1.test.main(test.java:1204)
Caused by: java.lang.ClassNotFoundException: org.reactivestreams.Publisher
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:419)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:352)

还有一种方法可以通过 AzureAD 应用程序获取 azureKeyVault Secret 值。

以下信息需要访问 keyVault。

Client Id

添加机密(客户端机密)

KeyVaultURL。

确保在创建 AzureKeyVault 时将 access policy 分配给密钥库。

现在保留所有默认值并查看+创建

使用 Java 访问 Azure Key Vault 需要这些依赖项。

已添加到 pom.xml 文件中

<properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

 <dependencies>
        <!-- https://mvnrepository.com/artifact/com.azure/azure-core -->
        <dependency>
            <groupId>com.microsoft.azure</groupId>
            <artifactId>msal4j</artifactId>
            <version>1.11.0</version>
        </dependency>
        <dependency>
            <groupId>com.microsoft.azure</groupId>
            <artifactId>azure</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.microsoft.azure</groupId>
            <artifactId>azure-keyvault</artifactId>
            <version>1.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
        </dependency>
    </dependencies>

Java 代码示例

package com.example.azure.keyvault;

import java.net.MalformedURLException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.microsoft.aad.adal4j.AuthenticationContext;
import com.microsoft.aad.adal4j.AuthenticationResult;
import com.microsoft.aad.adal4j.ClientCredential;
import com.microsoft.azure.keyvault.KeyVaultClient;
import com.microsoft.azure.keyvault.authentication.KeyVaultCredentials;
import com.microsoft.azure.keyvault.models.SecretBundle;


import java.util.concurrent.Future;

public class KeyVaultTest {

    private static AuthenticationResult getAccessToken(String authorization, String resource) throws InterruptedException, ExecutionException, MalformedURLException {

        String clientId = "XXXXXXXX"; // Client ID
        String clientKey = "XXXXXXXXXXXX";  //Client Secret

        AuthenticationResult result = null;

        //Starts a service to fetch access token.
        ExecutorService service = null;
        try {
            service = Executors.newFixedThreadPool(1);
            AuthenticationContext context = new AuthenticationContext(authorization, false, service);

            Future<AuthenticationResult> future = null;

            //Acquires token based on client ID and client secret.
            if (clientKey != null && clientKey != null) {
                ClientCredential credentials = new ClientCredential(clientId, clientKey);
                future = context.acquireToken(resource, credentials, null);
            }

            result = future.get();
        } finally {
            service.shutdown();
        }

        if (result == null) {
            throw new RuntimeException("Authentication results were null.");
        }
        return result;
    }

    public static void main(String[] args) {
        String vaultBase = "https://ohankeXXXXX.vault.azure.net/"; //KeyVaultURI

        KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultCredentials(){
            @Override
            public String doAuthenticate(String authorization, String resource, String scope) {
                String token = null;
                try {
                    AuthenticationResult authResult = getAccessToken(authorization, resource);
                    token = authResult.getAccessToken();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return token;
            }
        });

        SecretBundle test = keyVaultClient.getSecret(vaultBase, "test"); //created a secret in keyault with name test
        System.out.println(test.value());
    }
}

控制台输出

参考:1.http://www.stratogator.com/2017/10/20/how-to-access-secrets-in-azure-key-vault-using-java/ 2.