KeyVault 集成 - [致命错误]:1:1:文件过早结束
KeyVault integration - [Fatal Error] :1:1: Premature end of file
我一直在尝试编写一些基本代码来测试 Azure KeyVault。目前(正如您从控制台日志中看到的那样),我可以进行身份验证,但是 KeyVaultClient 只是失败并出现 [致命错误] :1:1: 过早结束文件.
Microsoft 似乎缺少与 azure-java-sdk 相关的真实示例,所以我承认我一直在努力尽我最大的努力解释 JavaDocs !
16:12:02.391 [main] DEBUG com.example.cli.Main - Launched !
16:12:02.453 [main] DEBUG e.s.cli.AzureAuthenticationResult -
Authresult getToken
16:12:02.491 [pool-1-thread-1] DEBUG
c.m.aad.adal4j.AuthenticationContext - [Correlation ID:
XXXXXXX-XXX-XXX-XXX-XXXXXXX] Using Client Http Headers:
x-client-SKU=java;x-client-VER=1.0.0;x-client-OS=XXXX;x-client-CPU=XXXX;return-client-request-id=true;client-request-id=XXXXXXX-XXX-XXX-XXX-XXXXXXX;
16:12:02.491 [pool-1-thread-1] INFO
c.m.a.adal4j.AuthenticationAuthority - [Correlation ID:
XXXXXXX-XXX-XXX-XXX-XXXXXXX] Instance discovery was successful
16:12:05.142 [pool-1-thread-1] DEBUG
c.m.aad.adal4j.AuthenticationContext - [Correlation ID:
XXXXXXX-XXX-XXX-XXX-XXXXXXX] Access Token with hash
'ZZZZZZZZZZZZZZZZZZZZZZZZ' returned
[Fatal Error] :1:1: Premature end
of file.
16:12:08.135 [main] ERROR com.example.cli.Main - null
java.util.concurrent.ExecutionException:
com.microsoft.windowsazure.exception.ServiceException:
at
java.util.concurrent.FutureTask.report(FutureTask.java:122)
~[na:1.8.0_45]
at
java.util.concurrent.FutureTask.get(FutureTask.java:192)
~[na:1.8.0_45]
at
com.microsoft.azure.keyvault.FutureAdapter.get(FutureAdapter.java:53)
~[azure-keyvault-0.9.0.jar:na]
at
com.example.cli.Main.main(Main.java:37) ~[classes/:na]
at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
~[na:1.8.0_45]
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
~[na:1.8.0_45]
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
~[na:1.8.0_45]
at java.lang.reflect.Method.invoke(Method.java:497)
~[na:1.8.0_45]
at
com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
[idea_rt.jar:na]
Caused by:
com.microsoft.windowsazure.exception.ServiceException:
at >com.microsoft.windowsazure.exception.ServiceException.createFromXml(ServiceException.java:216)
~[azure-core-0.9.0.jar:na]
at
com.microsoft.azure.keyvault.KeyOperationsImpl.sign(KeyOperationsImpl.java:1524)
~[azure-keyvault-0.9.0.jar:na]
at
com.microsoft.azure.keyvault.KeyOperationsImpl.call(KeyOperationsImpl.java:1447)
~[azure-keyvault-0.9.0.jar:na]
at >com.microsoft.azure.keyvault.KeyOperationsImpl.call(KeyOperationsImpl.java:1444)
~[azure-keyvault-0.9.0.jar:na]
at
java.util.concurrent.FutureTask.run(FutureTask.java:266)
~[na:1.8.0_45]
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
~[na:1.8.0_45]
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
~[na:1.8.0_45]
at java.lang.Thread.run(Thread.java:745)
~[na:1.8.0_45]
Process finished with exit code 0
package com.example.cli;
import com.microsoft.azure.keyvault.KeyVaultClient;
import com.microsoft.azure.keyvault.KeyVaultClientService;
import com.microsoft.azure.keyvault.models.KeyOperationResult;
import com.microsoft.azure.keyvault.webkey.JsonWebKeySignatureAlgorithm;
import com.microsoft.windowsazure.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.*;
import java.util.Random;
import java.util.concurrent.Future;
public class Main {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger(Main.class);
logger.debug("Launched !");
try {
byte[] plainText = new byte[100];
new Random(0x1234567L).nextBytes(plainText);
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(plainText);
byte[] digest = md.digest();
Configuration configuration = AzureKVCredentials.createConfiguration();
KeyVaultClient keyVaultClient = KeyVaultClientService.create(configuration);
Future<KeyOperationResult> keyOperationPromise;
KeyOperationResult keyOperationResult;
keyOperationPromise = keyVaultClient.signAsync("https://XXXXXXX.vault.azure.net/keys/XXXXXXX/XXXXXXX”,JsonWebKeySignatureAlgorithm.RS256,digest);
keyOperationResult = keyOperationPromise.get(); // <=== THIS IS LINE 37 IN THE STACKTRACE ;-) <====
byte[] res = keyOperationResult.getResult();
String b64 = java.util.Base64.getEncoder().encodeToString(res);
logger.debug(b64);
} catch (Exception e) {
logger.error(null,e);
}
}
}
对于使用Azure KeyVault,您可以尝试使用Azure REST APIs来管理和操作Key Vault。请参阅 Key Vault REST 文档 https://msdn.microsoft.com/en-us/library/azure/dn903630.aspx.
有两组用于 Key Vault 管理和 Keys & Secrets 操作的 API,它们需要来自不同资源 uri 的不同访问令牌。
对于管理 api,资源 uri 是 https://management.core.windows.net/
。
对于操作 api,资源 uri 是 https://vault.azure.net
。 (注意:请注意uri末尾没有符号/
。)
这里有一个示例代码作为参考。
package aad.keyvault;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.naming.ServiceUnavailableException;
import javax.net.ssl.HttpsURLConnection;
import org.apache.commons.io.IOUtils;
import com.microsoft.aad.adal4j.AuthenticationContext;
import com.microsoft.aad.adal4j.AuthenticationResult;
import com.microsoft.aad.adal4j.ClientCredential;
public class RestAPISample {
private static final String subscriptionId = "<subscription_id>";
private static final String resourceGroupName = "<resource_group_name>";
private static final String vaultName = "<vault_name>";
private static final String apiVersion = "2015-06-01";
private static final String getKeyVaultInfoUri = String.format(
"https://management.azure.com/subscriptions/%s/resourceGroups/%s/providers/Microsoft.KeyVault/vaults/%s?api-version=%s",
subscriptionId, resourceGroupName, vaultName, apiVersion);
private static final String tenantId = "<tenant_id>";
private static final String authority = String.format("https://login.windows.net/%s", tenantId);
private static final String clientId = "<client_id>";
private static final String clientSecret = "<client_secret_key>";
private static final String keyName = "<keyvault_key>";
private static final String getInfoFromAKeyUri = String.format("https://%s.vault.azure.net/keys/%s?api-version=%s",
vaultName, keyName, apiVersion);
public static String getAccessToken(String resource)
throws MalformedURLException, InterruptedException, ExecutionException, ServiceUnavailableException {
AuthenticationContext context = null;
AuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
context = new AuthenticationContext(authority, true, service);
ClientCredential credential = new ClientCredential(clientId, clientSecret);
Future<AuthenticationResult> future = context.acquireToken(resource, credential, null);
result = future.get();
} finally {
service.shutdown();
}
String accessToken = null;
if (result == null) {
throw new ServiceUnavailableException("authentication result was null");
} else {
accessToken = result.getAccessToken();
System.out.println("Access Token: " + accessToken);
}
return accessToken;
}
public static void getKeyVaultInfo() throws MalformedURLException, IOException, ServiceUnavailableException,
InterruptedException, ExecutionException {
System.out.println(getKeyVaultInfoUri);
HttpsURLConnection conn = (HttpsURLConnection) new URL(getKeyVaultInfoUri).openConnection();
conn.setRequestProperty("Authorization", "Bearer " + getAccessToken("https://management.core.windows.net/"));
conn.addRequestProperty("Content-Type", "application/json");
String resp = IOUtils.toString(conn.getInputStream());
System.out.println(resp);
}
public static void getKeyInfo() throws MalformedURLException, IOException, ServiceUnavailableException, InterruptedException, ExecutionException {
System.out.println(getInfoFromAKeyUri);
HttpsURLConnection conn = (HttpsURLConnection) new URL(getInfoFromAKeyUri).openConnection();
conn.setRequestProperty("Authorization", "Bearer " + getAccessToken("https://vault.azure.net"));
conn.addRequestProperty("Content-Type", "application/json");
String resp = IOUtils.toString(conn.getInputStream());
System.out.println(resp);
}
public static void main(String[] args)
throws InterruptedException, ExecutionException, ServiceUnavailableException, IOException {
getKeyVaultInfo();
getKeyInfo();
}
}
Azure Key Vault 操作 API 需要使用命令 set-policy
设置不同的权限。例如Get information about a key
(https://msdn.microsoft.com/en-us/library/azure/dn878080.aspx),它需要授权需要keys/get权限,使用Azure CLI cmd azure keyvault set-policy --vault-name <vault-name> --spn <service-principal-no.> --perms-to-keys '["get"]'
给密钥添加权限get
。
你的代码对我有用,所以我怀疑你的凭据对象(你没有提供)无效。特别是,请确保使用 KeyVaultConfiguration
实例。
这是我的工作版本 AzureKVCredentials
:
package com.example.cli;
import java.util.*;
import java.util.concurrent.*;
import com.microsoft.aad.adal4j.*;
import org.apache.http.*;
import org.apache.http.message.*;
import com.microsoft.azure.keyvault.*;
import com.microsoft.azure.keyvault.authentication.*;
import com.microsoft.windowsazure.*;
import com.microsoft.windowsazure.core.pipeline.filter.*;
public class AzureKVCredentials extends KeyVaultCredentials {
public static Configuration createConfiguration() {
return KeyVaultConfiguration.configure(null, new AzureKVCredentials());
}
@Override
public Header doAuthenticate(ServiceRequestContext request, Map<String, String> challenge) {
try {
String authorization = challenge.get("authorization");
String resource = challenge.get("resource");
AuthenticationResult authResult = getAccessToken(authorization, resource);
return new BasicHeader("Authorization", authResult.getAccessTokenType() + " " + authResult.getAccessToken());
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private static AuthenticationResult getAccessToken(String authorization, String resource) throws Exception {
String clientId = "<app id of your Azure application>";
String clientKey = "<application key>";
AuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
AuthenticationContext context = new AuthenticationContext(authorization, false, service);
Future<AuthenticationResult> future = 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 result was null");
}
return result;
}
}
此代码基于 azure-sdk-for-java.
中的 these sources
我一直在尝试编写一些基本代码来测试 Azure KeyVault。目前(正如您从控制台日志中看到的那样),我可以进行身份验证,但是 KeyVaultClient 只是失败并出现 [致命错误] :1:1: 过早结束文件.
Microsoft 似乎缺少与 azure-java-sdk 相关的真实示例,所以我承认我一直在努力尽我最大的努力解释 JavaDocs !
16:12:02.391 [main] DEBUG com.example.cli.Main - Launched ! 16:12:02.453 [main] DEBUG e.s.cli.AzureAuthenticationResult - Authresult getToken
16:12:02.491 [pool-1-thread-1] DEBUG c.m.aad.adal4j.AuthenticationContext - [Correlation ID: XXXXXXX-XXX-XXX-XXX-XXXXXXX] Using Client Http Headers: x-client-SKU=java;x-client-VER=1.0.0;x-client-OS=XXXX;x-client-CPU=XXXX;return-client-request-id=true;client-request-id=XXXXXXX-XXX-XXX-XXX-XXXXXXX;
16:12:02.491 [pool-1-thread-1] INFO c.m.a.adal4j.AuthenticationAuthority - [Correlation ID: XXXXXXX-XXX-XXX-XXX-XXXXXXX] Instance discovery was successful
16:12:05.142 [pool-1-thread-1] DEBUG c.m.aad.adal4j.AuthenticationContext - [Correlation ID: XXXXXXX-XXX-XXX-XXX-XXXXXXX] Access Token with hash 'ZZZZZZZZZZZZZZZZZZZZZZZZ' returned
[Fatal Error] :1:1: Premature end of file.
16:12:08.135 [main] ERROR com.example.cli.Main - null java.util.concurrent.ExecutionException: com.microsoft.windowsazure.exception.ServiceException:
at java.util.concurrent.FutureTask.report(FutureTask.java:122) ~[na:1.8.0_45]at java.util.concurrent.FutureTask.get(FutureTask.java:192) ~[na:1.8.0_45]
at com.microsoft.azure.keyvault.FutureAdapter.get(FutureAdapter.java:53) ~[azure-keyvault-0.9.0.jar:na]
at com.example.cli.Main.main(Main.java:37) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_45]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_45]
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) [idea_rt.jar:na]Caused by: com.microsoft.windowsazure.exception.ServiceException:
at >com.microsoft.windowsazure.exception.ServiceException.createFromXml(ServiceException.java:216) ~[azure-core-0.9.0.jar:na]
at com.microsoft.azure.keyvault.KeyOperationsImpl.sign(KeyOperationsImpl.java:1524) ~[azure-keyvault-0.9.0.jar:na]
at com.microsoft.azure.keyvault.KeyOperationsImpl.call(KeyOperationsImpl.java:1447) ~[azure-keyvault-0.9.0.jar:na] at >com.microsoft.azure.keyvault.KeyOperationsImpl.call(KeyOperationsImpl.java:1444) ~[azure-keyvault-0.9.0.jar:na]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_45]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) ~[na:1.8.0_45]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) ~[na:1.8.0_45]
at java.lang.Thread.run(Thread.java:745) ~[na:1.8.0_45]Process finished with exit code 0
package com.example.cli;
import com.microsoft.azure.keyvault.KeyVaultClient;
import com.microsoft.azure.keyvault.KeyVaultClientService;
import com.microsoft.azure.keyvault.models.KeyOperationResult;
import com.microsoft.azure.keyvault.webkey.JsonWebKeySignatureAlgorithm;
import com.microsoft.windowsazure.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.*;
import java.util.Random;
import java.util.concurrent.Future;
public class Main {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger(Main.class);
logger.debug("Launched !");
try {
byte[] plainText = new byte[100];
new Random(0x1234567L).nextBytes(plainText);
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(plainText);
byte[] digest = md.digest();
Configuration configuration = AzureKVCredentials.createConfiguration();
KeyVaultClient keyVaultClient = KeyVaultClientService.create(configuration);
Future<KeyOperationResult> keyOperationPromise;
KeyOperationResult keyOperationResult;
keyOperationPromise = keyVaultClient.signAsync("https://XXXXXXX.vault.azure.net/keys/XXXXXXX/XXXXXXX”,JsonWebKeySignatureAlgorithm.RS256,digest);
keyOperationResult = keyOperationPromise.get(); // <=== THIS IS LINE 37 IN THE STACKTRACE ;-) <====
byte[] res = keyOperationResult.getResult();
String b64 = java.util.Base64.getEncoder().encodeToString(res);
logger.debug(b64);
} catch (Exception e) {
logger.error(null,e);
}
}
}
对于使用Azure KeyVault,您可以尝试使用Azure REST APIs来管理和操作Key Vault。请参阅 Key Vault REST 文档 https://msdn.microsoft.com/en-us/library/azure/dn903630.aspx.
有两组用于 Key Vault 管理和 Keys & Secrets 操作的 API,它们需要来自不同资源 uri 的不同访问令牌。
对于管理 api,资源 uri 是 https://management.core.windows.net/
。
对于操作 api,资源 uri 是 https://vault.azure.net
。 (注意:请注意uri末尾没有符号/
。)
这里有一个示例代码作为参考。
package aad.keyvault;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.naming.ServiceUnavailableException;
import javax.net.ssl.HttpsURLConnection;
import org.apache.commons.io.IOUtils;
import com.microsoft.aad.adal4j.AuthenticationContext;
import com.microsoft.aad.adal4j.AuthenticationResult;
import com.microsoft.aad.adal4j.ClientCredential;
public class RestAPISample {
private static final String subscriptionId = "<subscription_id>";
private static final String resourceGroupName = "<resource_group_name>";
private static final String vaultName = "<vault_name>";
private static final String apiVersion = "2015-06-01";
private static final String getKeyVaultInfoUri = String.format(
"https://management.azure.com/subscriptions/%s/resourceGroups/%s/providers/Microsoft.KeyVault/vaults/%s?api-version=%s",
subscriptionId, resourceGroupName, vaultName, apiVersion);
private static final String tenantId = "<tenant_id>";
private static final String authority = String.format("https://login.windows.net/%s", tenantId);
private static final String clientId = "<client_id>";
private static final String clientSecret = "<client_secret_key>";
private static final String keyName = "<keyvault_key>";
private static final String getInfoFromAKeyUri = String.format("https://%s.vault.azure.net/keys/%s?api-version=%s",
vaultName, keyName, apiVersion);
public static String getAccessToken(String resource)
throws MalformedURLException, InterruptedException, ExecutionException, ServiceUnavailableException {
AuthenticationContext context = null;
AuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
context = new AuthenticationContext(authority, true, service);
ClientCredential credential = new ClientCredential(clientId, clientSecret);
Future<AuthenticationResult> future = context.acquireToken(resource, credential, null);
result = future.get();
} finally {
service.shutdown();
}
String accessToken = null;
if (result == null) {
throw new ServiceUnavailableException("authentication result was null");
} else {
accessToken = result.getAccessToken();
System.out.println("Access Token: " + accessToken);
}
return accessToken;
}
public static void getKeyVaultInfo() throws MalformedURLException, IOException, ServiceUnavailableException,
InterruptedException, ExecutionException {
System.out.println(getKeyVaultInfoUri);
HttpsURLConnection conn = (HttpsURLConnection) new URL(getKeyVaultInfoUri).openConnection();
conn.setRequestProperty("Authorization", "Bearer " + getAccessToken("https://management.core.windows.net/"));
conn.addRequestProperty("Content-Type", "application/json");
String resp = IOUtils.toString(conn.getInputStream());
System.out.println(resp);
}
public static void getKeyInfo() throws MalformedURLException, IOException, ServiceUnavailableException, InterruptedException, ExecutionException {
System.out.println(getInfoFromAKeyUri);
HttpsURLConnection conn = (HttpsURLConnection) new URL(getInfoFromAKeyUri).openConnection();
conn.setRequestProperty("Authorization", "Bearer " + getAccessToken("https://vault.azure.net"));
conn.addRequestProperty("Content-Type", "application/json");
String resp = IOUtils.toString(conn.getInputStream());
System.out.println(resp);
}
public static void main(String[] args)
throws InterruptedException, ExecutionException, ServiceUnavailableException, IOException {
getKeyVaultInfo();
getKeyInfo();
}
}
Azure Key Vault 操作 API 需要使用命令 set-policy
设置不同的权限。例如Get information about a key
(https://msdn.microsoft.com/en-us/library/azure/dn878080.aspx),它需要授权需要keys/get权限,使用Azure CLI cmd azure keyvault set-policy --vault-name <vault-name> --spn <service-principal-no.> --perms-to-keys '["get"]'
给密钥添加权限get
。
你的代码对我有用,所以我怀疑你的凭据对象(你没有提供)无效。特别是,请确保使用 KeyVaultConfiguration
实例。
这是我的工作版本 AzureKVCredentials
:
package com.example.cli;
import java.util.*;
import java.util.concurrent.*;
import com.microsoft.aad.adal4j.*;
import org.apache.http.*;
import org.apache.http.message.*;
import com.microsoft.azure.keyvault.*;
import com.microsoft.azure.keyvault.authentication.*;
import com.microsoft.windowsazure.*;
import com.microsoft.windowsazure.core.pipeline.filter.*;
public class AzureKVCredentials extends KeyVaultCredentials {
public static Configuration createConfiguration() {
return KeyVaultConfiguration.configure(null, new AzureKVCredentials());
}
@Override
public Header doAuthenticate(ServiceRequestContext request, Map<String, String> challenge) {
try {
String authorization = challenge.get("authorization");
String resource = challenge.get("resource");
AuthenticationResult authResult = getAccessToken(authorization, resource);
return new BasicHeader("Authorization", authResult.getAccessTokenType() + " " + authResult.getAccessToken());
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private static AuthenticationResult getAccessToken(String authorization, String resource) throws Exception {
String clientId = "<app id of your Azure application>";
String clientKey = "<application key>";
AuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
AuthenticationContext context = new AuthenticationContext(authorization, false, service);
Future<AuthenticationResult> future = 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 result was null");
}
return result;
}
}
此代码基于 azure-sdk-for-java.
中的 these sources