java - 我如何从 keystore 中获取 secret ?

标签 java azure spring-boot azure-keyvault

我想从 Azure key 保管库获取 secret 。

我找到了下面的代码并尝试了它。 但我因错误而失败。

    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

我如何从 keystore 中获取 secret ? 还有什么我应该做的吗?

谢谢。

最佳答案

您似乎想通过应用程序访问 azure key 保管库。

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

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

  3. 添加 secret enter image description here

  4. 在 key 保管库中分配访问策略 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());
    }
}

<小时/>

更新:

如果您遇到连接问题,请检查您是否为 key 保管库设置了防火墙。

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

enter image description here

关于java - 我如何从 keystore 中获取 secret ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57765760/

相关文章:

java - Stripe : How do i know whether card is 3d secure and how to charge it

java - Android 中更好的文字转语音

azure - 使用 ARM 模板创建 Azure 自动化 Runbook Webhook?

java - 从 JSONObject 提取值并将其复制到 HashMap

spring-boot - 如何将现有用户角色映射到 keycloak 中的自定义用户存储提供程序?

java - 长度可变的字节数组

java - 从 appengine 验证 UserService

azure - 微软翻译 API 3.0 到 HTML

Azure 批量插入 : Bad Request Error

spring-boot - NoSuchMethodException QueryDSL 与 Spring Boot 和 Spring Data Mongo