Azure KeyVaultClient:使用Java证书进行身份验证

时间:2017-01-09 13:52:30

标签: java azure azure-keyvault

我正在尝试从pfx证书的KeyVaultClient创建一个Azure Java SDK对象。我在C#中找到了一个关于如何做到这一点的明确文档,但必须弄清楚如何在Java中做到这一点。

我可以从用户帐户keystore获取Windows证书,但我真的不知道要传递给KeyVaultClient构造函数的内容。看起来它接受TokenCredentials类型的对象,但我找不到任何关于如何实际构建其中一个(需要“令牌”和“方案”)的文档。

2 个答案:

答案 0 :(得分:0)

通过定义这个类,似乎我已经接近了一些工作:

  class WindowsStoreCertificateCredentials(clientId: String, certificate: X509Certificate, privateKey: PrivateKey) extends KeyVaultCredentials {

def getAuthResult(authority: String, resource: String): AuthenticationResult  = {       
  val service  = Executors.newFixedThreadPool(1)
  val context = new AuthenticationContext(authority, false, service)

  val certificateCredentials = AsymmetricKeyCredential.create(clientId, privateKey, certificate)
  val authResultFuture = context.acquireToken(resource, certificateCredentials, null)
  authResultFuture.get
}

override def doAuthenticate (authority: String, resource: String, scope: String): String = {
  getAuthResult(authority, resource).getAccessToken
}

}

在使用java.security.KeyStore获取证书X509Certificate对象和私钥后尝试使用它:

val client = new KeyVaultClient(new WindowsStoreCertificateCredentials(
  id, privateKey, certificate,))

val test = client.getSecret("https:/...")

不幸的是它引发了一个例外:

sun.security.mscapi.RSAPrivateKey cannot be cast to java.security.interfaces.RSAPrivateKey java.lang.ClassCastException:  sun.security.mscapi.RSAPrivateKey cannot be cast to java.security.interfaces.RSAPrivateKey

我在github AzureAD / azure-activedirectory-library-for-java上打开了一个问题,并提出了一个拉取请求来修复它,继续......

编辑:现在修复了AzureAD / azure-activedirectory-library-for-java 1.2.0版本。

答案 1 :(得分:-1)

听起来您想知道如何使用Azure SDK for Java通过带有所需参数KeyVaultClient的构造函数方法创建ServiceClientCredentials credentials对象,如javadoc所述。< / p>

这是我的示例代码。

import com.microsoft.azure.AzureEnvironment;
import com.microsoft.azure.CloudException;
import com.microsoft.azure.credentials.ApplicationTokenCredentials;
import com.microsoft.azure.keyvault.KeyVaultClient;
import com.microsoft.azure.management.Azure;
import com.microsoft.rest.credentials.ServiceClientCredentials;

String clientId = "xxxx";
String domain = "xxxx";  // The same as tenant_id
String secret = "xxxx";  // The same as client_secret or keys
AzureEnvironment environment = AzureEnvironment.AZURE;
ServiceClientCredentials credentials = new ApplicationTokenCredentials(clientId, domain, secret, environment);
// New a KeyVaultClient object
KeyVaultClient kvClient = new KeyValutClient(credentials);

作为参考,您可以参考Azure官方document获取参数clientIddomain&amp; Azure管理门户上的secret。有关Azure Java SDK API的更多详细信息,请查看javadocs