Search code examples
serviceazure-service-fabricazure-keyvault

Accessing Secrets on Azure Key Vault from Service Fabric


I build service fabric application and I want to secure secrets in Azure Key vault, I implement the same steps I do for app service but it doesn't work, appreciating your replay.

For App Service: 1. Configure Key Vault on Main Method 2. Enable assigned managed identity on App Service, applied on Scale set for SF. 3. Add access policy on the key vault.


Solution

  • 1) Azure configuration (VM Scale set + Key vault):

    Login-AzureRmAccount # Login into Azure account
    
    $targetRg = "testfabric-rg" # Target resource group name
    $targetVmss = "jxewcyinq" # Target virtual machine scale set name
    $targetKeyVault = "az-ure-two20190115153549" # Target Key Vault name
    
    # 1. Enable Managed Identity for target Virtual Machine Scale Set
    Update-AzureRmVmss `
        -ResourceGroupName $targetRg `
        -VMScaleSetName $targetVmss `
        -IdentityType SystemAssigned
    # 2. Retrieve virtual machine scale set
    $vmss = Get-AzureRmVmss `
        -ResourceGroupName $targetRg `
        -Name $targetVmss
    # 3. Create new Key vault access policy allowing Virtual Machine Scale Set to read secrets by their IDs
    Set-AzureRmKeyVaultAccessPolicy `
        -VaultName $targetKeyVault `
        -ObjectId $vmss.Identity.PrincipalId `
        -PermissionsToSecrets Get # set only necessary permissions!
    

    2) Get key vault secret when using C#:

    // https://www.nuget.org/packages/Microsoft.Azure.KeyVault/
    using Microsoft.Azure.KeyVault;
    // https://www.nuget.org/packages/Microsoft.Azure.Services.AppAuthentication
    using Microsoft.Azure.Services.AppAuthentication;
    
    public async Task<string> GetSecretById(string id)
    {
        // URL of the target Key Vault
        var keyVaultUrl = "https://az-ure-two20190115153549.vault.azure.net";
    
        var azureServiceTokenProvider = new AzureServiceTokenProvider();
    
        var keyVaultClient = new KeyVaultClient(
            new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
    
        var secret = await keyVaultClient.GetSecretAsync($"{keyVaultUrl}/secrets/{id}");
    
        return secret.Value;
    }