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

Azure KeyVault - Use certificate and certificate private key

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

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

我想了解如何使用 Azure KeyVault 获取这些值 Java API.

此外,请告诉我如何获取 Azure 用户客户端 ID 和客户端密钥?

其实不用keyvault rest api, you could use java SDK for keyvault to 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. The sample is to get secret, just use the method KeyVaultClient.getCertificate 中的步骤最终获取证书而不是获取密钥。

注意:不要忘记在keyvault的Access Policies中添加你的AD应用,否则你的应用将没有权限。

除了,你应该注意client-id(即application id)和client-key是针对Azure AD应用程序而不是用户,它们都在示例文档中提到。或者更多详情,您可以参考:Create an Azure Active Directory application and create a secret for the app, save the secret by yourself and get values for signing in.