[英]Getting secret from Azure key vault
我试图从 azure 密钥保管库中获取秘密。
所以我找到了下面的代码,但出现错误。
AppServiceMSICredentials credentials = new AppServiceMSICredentials(AzureEnvironment.AZURE);
KeyVaultClient keyVaultClient = new KeyVaultClient(credentials);
String secret = keyVaultClient.getSecret("uri", "secretName").value();
我收到这样的错误:
Error >>> endpoint == null
我也试过这种方式:
AppServiceMSICredentials credentials = new AppServiceMSICredentials(AzureEnvironment.AZURE, "MSI Url????", "secret???");
KeyVaultClient keyVaultClient = new KeyVaultClient(credentials);
String secret = keyVaultClient.getSecret("keyVault Uri", "secret name").value();
log.debug("secret=========",secret);
我是 Azure 的新手,现在找不到解决方案....
我该如何解决? 另外我怎样才能找到 msi 端点和秘密?
谢谢你。
您使用的是托管标识。 您不需要提供任何端点或秘密。
您唯一需要做的就是在您的 Web 应用程序中启用系统标识。
之后,您将获得服务主体的对象 ID。 然后您可以在您的密钥保管库中为该服务主体分配访问策略。
最后,您可以在 Spring Boot 应用程序中访问您的密钥保管库和密钥。
更新:
如果无法创建托管标识,则可以使用 Azure AD 库获取访问令牌。 然后使用该令牌访问密钥保管库。
这是一个代码示例:
public class KeyVaultTest {
// Add access policy to user, and access key vault as user
private static AuthenticationResult getAccessTokenAsUser(String authorization, String resource) throws InterruptedException, ExecutionException, MalformedURLException {
String clientId = "1950a258-227b-4e31-a9cf-717495945fc2";
String username = "your user id, jack@hanxia.onmicrosoft.com";
String password = "your password, ********";
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 = context.acquireToken(resource, clientId, username, password, 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://keyvault279.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 = getAccessTokenAsUser(authorization, resource);
token = authResult.getAccessToken();
} catch (Exception e) {
e.printStackTrace();
}
return token;
}
});
SecretBundle test = keyVaultClient.getSecret(vaultBase, "test");
System.out.println(test.value());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.