如何从密钥库中获取秘密?

时间:2019-09-03 05:55:46

标签: java azure spring-boot azure-keyvault

我想从Azure密钥库中获取秘密。

我在下面找到了代码并进行了尝试。 但是我失败了。

    private String clientId= '<I put my client Id here>';
    private String secret= '<I put my client secret here>';



KeyVaultClient client = new KeyVaultClient(credentials);

String secret = client.getSecret("https://<myVault>.vault.azure.net", "secret name").value();
        log.debug("secret=============",secret);
    }


    ServiceClientCredentials credentials = new KeyVaultCredentials() {

        @Override
        public String doAuthenticate(String authorization, String resource, String scope) {
            AuthenticationResult res = null;

            try {
                res = GetAccessToken(authorization, resource, clientId, secret);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                return res.getAccessToken();
        }

        private AuthenticationResult GetAccessToken(String authorization, String resource, String clientID, String clientKey)
                throws InterruptedException, ExecutionException {
            AuthenticationContext ctx = null;
            ExecutorService service = Executors.newFixedThreadPool(1);
            try {
                ctx = new AuthenticationContext(authorization, false, service);
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Future<AuthenticationResult> resp = ctx.acquireToken(resource, new ClientCredential(
                clientID, clientKey), null);
                AuthenticationResult res = resp.get();
                return res;
            }

我收到如下错误:

[http-nio-8080-exec-1] ERROR c.t.c.e.GlobalExceptionHandler - Error >>> java.net.ConnectException: Failed to connect

如何从密钥库中获取秘密? 我还有什么需要做的吗?

谢谢。

2 个答案:

答案 0 :(得分:2)

似乎您想使用应用程序访问azure密钥库。

  1. 在Azure AD中注册Web应用 enter image description here

  2. 您可以在概述中获取客户端ID(应用程序ID) enter image description here

  3. 添加秘密 enter image description here

  4. 在密钥库中分配访问策略 enter image description here

  5. 保存该策略,以使其生效。

  6. 代码示例

public class KeyVaultTest {

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

        String clientId = "dc17****-****-****-****-ea03****a5e7"; // Client ID
        String clientKey = "1YWt******k21";  //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://jackkv.vault.azure.net/";

        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");
        System.out.println(test.value());
    }
}


更新

如果遇到连接问题,请检查是否已为密钥库设置了防火墙。

如果设置了防火墙,请将IP添加到允许的列表中:

enter image description here

答案 1 :(得分:1)

在从Azure密钥保管库获取机密之前,请确保您有权访问密钥保管库。确保登录或提供正确的Azure凭据。 you can refer this link for getting secret

或者您执行此powershell命令Get-AzureKeyVaultSecret -VaultName 'VaultName' -Name 'sceretName'

相关问题