6

I'm trying to access KeyVault from an .net Core console application, using a Service Principle (I have the App Id and App Secret). Here's my code:

var client = new KeyVaultClient(GetAccessToken);
var secret = client.GetSecretAsync("https://{keyvaultName}.vault.azure.net", "MySecret").Result; 

Which calls back to this function:

private static async Task<string> GetAccessToken(string authority, string resource, string scope)
{
    var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
    var credential = new ClientCredential(clientId: appId, clientSecret: appSecret);

    var authResult = await context.AcquireTokenAsync(resource, credential);
    return authResult.AccessToken;
}

Calling GetSecretAsync returns an "AccessDenied" exception. Modifying the code to use this callback yeilds an "Unauthorized" exception:

private static async Task<string> GetAccessToken(string authority, string resource, string scope)
{
    var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
    var credential = new ClientCredential(clientId: appId, clientSecret: appSecret);

    **var authResult = await context.AcquireTokenAsync("https://management.core.windows.net/", credential);**
    return authResult.AccessToken;
}

I setup the Service Principle by going to Azure > AAD > App Registrations, noted the App Id and password (App Secret) when I setup the Principle.

Then in KeyVault, I added the principle to Access Control (IAM), with contributor rights, but still no joy!

Has anyone come across this scenario before?

Thanks! :)

4

2 回答 2

8

我用下面的代码测试它,它在我这边正常工作。resourceUri 是https://vault.azure.net.

static string appId = "xxxxxxxxxxxxx";
static string appSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
static string tenantId = "xxxxxxxxxxxxxxxxxxxxx";
public static void Main(string[] args)
{
    var kv = new KeyVaultClient(GetAccessToken);
    var scret = kv.GetSecretAsync("https://xxxxxx.vault.azure.net", "secretname").GetAwaiter().GetResult();
}

public static async Task<string> GetAccessToken(string azureTenantId, string clientId, string redirectUri)
{
    var context = new AuthenticationContext("https://login.windows.net/" + tenantId);
    var credential = new ClientCredential(appId, appSecret);
    var tokenResult = await context.AcquireTokenAsync("https://vault.azure.net", credential);
   return tokenResult.AccessToken;
}

此外,您需要向注册的应用程序添加“Key Vault”权限。 在此处输入图像描述

在 Key Vault 通道中,您需要向注册的应用程序或用户添加策略。在访问控制中,您需要为注册的应用程序或用户添加权限。 在此处输入图像描述 在此处输入图像描述

输出如下:在此处输入图像描述

于 2018-08-29T02:54:29.943 回答
3

“访问控制 (IAM)” 控制对保管库本身的访问。有一种单独的方法可以控制对保险库内容的访问(即:密钥、机密和证书)。如这些文档中所述,我们可以授权给定的 AAD 应用程序通过导航到所需的保险库、选择“访问策略”、单击“添加新”,然后搜索您的服务来检索 Azure 门户中给定保险库中的机密主要的。您应该能够按应用程序 ID 过滤:

在此处输入图像描述 在此处输入图像描述

于 2018-08-29T00:12:55.573 回答