Azure KeyVault-使用证书和证书私钥

时间:2019-06-05 14:30:57

标签: azure azure-keyvault

我正在研究一个需要使用自签名证书的用例,这些证书是使用Azure Key Vault创建的。

我的应用程序需要证书密钥和证书私钥进行身份验证。

我想了解如何通过使用Azure KeyVault Java API获得这些值。

还,请让我知道如何获取Azure用户的client-id和client-key?

1 个答案:

答案 0 :(得分:1)

实际上,不需要使用keyvault rest api,您可以使用Java SDK来对get certificate进行密钥存储。

package com.example.azure.keyvault;

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

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Based on example from Microsoft documentation:
 * https://azure.github.io/azure-sdk-for-java/com/microsoft/azure/keyvault/authentication/KeyVaultCredentials.html
 */
public class ClientSecretKeyVaultCredential extends KeyVaultCredentials
{
    private String clientId;
    private String clientKey;

    public ClientSecretKeyVaultCredential( String clientId, String clientKey ) {
        this.clientId = clientId;
        this.clientKey = clientKey;
    }

    @Override
    public String doAuthenticate(String authorization, String resource, String scope) {
        AuthenticationResult token = getAccessTokenFromClientCredentials(
                authorization, resource, clientId, clientKey);
        return token.getAccessToken();
    }

    private static AuthenticationResult getAccessTokenFromClientCredentials(
            String authorization, String resource, String clientId, String clientKey) {
        AuthenticationContext context = null;
        AuthenticationResult result = null;
        ExecutorService service = null;
        try {
            service = Executors.newFixedThreadPool(1);
            context = new AuthenticationContext(authorization, false, service);
            ClientCredential credentials = new ClientCredential(clientId, clientKey);
            Future<AuthenticationResult> future = context.acquireToken(
                    resource, credentials, null);
            result = future.get();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            service.shutdown();
        }

        if (result == null) {
            throw new RuntimeException("authentication result was null");
        }
        return result;
    }
}

有关更多详细信息,您可以按照此sample中的步骤进行操作。该示例是要保密的,仅使用方法KeyVaultClient.getCertificate来最后获得证书而不是保密。

注意:请不要忘记将AD App添加到密钥库的Access Policies中,否则您的应用将没有权限。

此外,您应该注意client-id(即application id)和client-key是针对Azure AD应用程序而不是用户的,它们在样本文档或者,有关更多详细信息,您可以参考:Create an Azure Active Directory applicationcreate a secret for the app,自己和get values for signing in保存机密。