【问题标题】:Fetch Azure KeyVault Secret using Java使用 Java 获取 Azure KeyVault 机密
【发布时间】:2022-01-26 20:42:08
【问题描述】:

我在使用 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)

【问题讨论】:

    标签: java azure azure-keyvault


    【解决方案1】:

    还有一种方法可以让您使用 AzureAD 应用程序获取 azureKeyVault Secret 值。

    以下信息需要访问 keyVault。

    Client Id

    添加密码(客户端密码)

    KeyVaultURL。

    确保在创建 AzureKeyVault 时将 access policy 分配给 keyvault。

    现在将所有内容保留为默认值并查看+创建

    使用 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.How can i get secret from key vault?

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 1970-01-01
      • 2020-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-08
      • 2021-08-09
      相关资源
      最近更新 更多