项目作者: Azure-Samples

项目描述 :
An ASP.NET Core app for bootstrapping your next Web Apps for Containers service using Key Vault and Managed Identities
高级语言: C#
项目地址: git://github.com/Azure-Samples/app-service-managed-identity-key-vault-csharp.git



services:

  • app-service
  • key-vault
  • azure-app-service
  • azure-key-vault
    platforms:
  • dotnet
  • linux
    languages:
  • csharp
    products:
  • azure
  • dotnet
  • aspnet
  • azure-app-service
  • azure-key-vault
    author: aflinchb
    description: “A sample ASP.NET Core WebAPI for bootstrapping your next App Service app using Managed Identity and Key Vault”
    urlFragment: app-service-managed-identity-key-vault-csharp
    page_type: sample

Build an ASP.NET Core application using App Service, Managed Identity and Key Vault

This sample is an ASP.NET Core WebAPI application designed to “fork and code” with the following features:

  • Securely build, deploy and run an App Service (Web App for Containers) application
  • Securely store secrets in Key Vault
  • Securely use Key Vault secrets as Application Settings values with Key Vault reference strings
  • Use Managed Identity to securely access Key Vault secrets from App Services
  • Use Managed Identity to securely access Docker images from Container Registry

Prerequisites

  • Azure subscription with permissions to create:
    • Resource Group, Keyvault, App Service, Azure Container Registry
  • Bash shell (tested on Mac, Ubuntu, WSL2 and Cloud Shell)
  • Azure CLI (download)
  • Docker CLI (download)
  • .NET Core SDK (download)
  • Visual Studio Code (optional) (download)

Open with Codespaces

You must have access to Codespaces as an individual or part of a GitHub Team or GitHub Enterprise Cloud

  • Click the Code button on your repo
    • Click the Codespaces tab
    • Click New Codespace

Setup

  • Fork this repo and clone to your local machine (unless using Codespaces)
    • cd to the base directory of the repo

Login to Azure and select subscription

  1. az login
  2. # show your Azure accounts
  3. az account list -o table
  4. # select the Azure account (if necessary)
  5. az account set -s {subscription name or Id}

Choose a unique DNS name

  1. # this will be the prefix for all resources
  2. # do not include punctuation - only use a-z and 0-9
  3. # must be at least 5 characters long
  4. # must start with a-z (only lowercase)
  5. export MIKV_NAME=myname
  6. ### if nslookup doesn't fail to resolve, change MIKV_NAME
  7. nslookup $MIKV_NAME.azurewebsites.net
  8. nslookup $MIKV_NAME.vault.azure.net
  9. nslookup $MIKV_NAME.azurecr.io

Create Resource Group

  • When experimenting with this sample, you should create a new resource group to avoid accidentally deleting resources
    • If you use an existing resource group, please make sure to apply resource locks to avoid accidentally deleting resources
  1. # set location
  2. export MIKV_LOCATION=centralus
  3. # MySecret URI
  4. export MIKV_SECRET_URI=https://$MIKV_NAME.vault.azure.net/secrets/MySecret
  5. # resource group name
  6. export MIKV_RG=${MIKV_NAME}-rg
  7. # create the resource group
  8. az group create -n $MIKV_RG -l $MIKV_LOCATION

Save your environment variables for ease of reuse and picking up where you left off

  1. # run the saveenv.sh script at any time to save MIKV_* variables to ~/${MIKV_NAME}.env
  2. ./saveenv.sh -y
  3. # at any point if your terminal environment gets cleared, you can source the file
  4. # you only need to remember the name of the env file
  5. source ~/YourUniqueName.env

Create Azure Key Vault

  • All secrets are stored in Azure Key Vault for security
    • Use System Managed Identity to access Key Vault
  1. ## create the Key Vault
  2. az keyvault create -g $MIKV_RG -n $MIKV_NAME
  3. # add a secret
  4. az keyvault secret set \
  5. --vault-name $MIKV_NAME \
  6. --name "MySecret" \
  7. --value "Hello from Key Vault and Managed Identity"

Create Azure Container Registry

Create the ACR with admin access disabled for security

  1. # create the ACR
  2. az acr create --sku Standard --admin-enabled false -g $MIKV_RG -n $MIKV_NAME
  3. # get the ACR_ID
  4. export MIKV_ACR_ID=$(az acr show -g $MIKV_RG -n $MIKV_NAME --query id --output tsv)
  5. # login to ACR
  6. # if you get an error that the login server isn't available,
  7. # it's a DNS issue that will resolve in a minute or two, just retry
  8. az acr login -n $MIKV_NAME --expose-token
  9. # build the mikv container
  10. az acr build -r $MIKV_NAME -t $MIKV_NAME.azurecr.io/mikv .

Create App Service

App Service will fail to start until configured properly

  1. # create App Service plan
  2. az appservice plan create --sku B1 --is-linux -g $MIKV_RG -n ${MIKV_NAME}-plan
  3. # create Web App for Containers with System Managed Identity
  4. # the hello-world image is a placeholder
  5. az webapp create \
  6. --deployment-container-image-name hello-world \
  7. --assign-identity '[system]' \
  8. -g $MIKV_RG \
  9. -n $MIKV_NAME \
  10. -p ${MIKV_NAME}-plan
  11. # stop the Web App while we update the config
  12. az webapp stop -g $MIKV_RG -n $MIKV_NAME

Grant access to Managed Identity

  1. # get the App Service Managed Identity
  2. export MIKV_MI_ID=$(az webapp identity show -g $MIKV_RG -n $MIKV_NAME --query principalId -o tsv)
  3. # grant Key Vault access to Managed Identity
  4. az keyvault set-policy \
  5. -n $MIKV_NAME \
  6. --secret-permissions get list \
  7. --key-permissions get list \
  8. --object-id $MIKV_MI_ID
  9. # grant acr pull access to the Managed Identity
  10. az role assignment create \
  11. --assignee $MIKV_MI_ID \
  12. --scope $MIKV_ACR_ID \
  13. --role acrpull

Configure Web App

  1. # turn on container logging
  2. az webapp log config \
  3. --docker-container-logging filesystem \
  4. -g $MIKV_RG \
  5. -n $MIKV_NAME
  6. # inject Key Vault secret
  7. az webapp config appsettings set \
  8. -g $MIKV_RG \
  9. -n $MIKV_NAME \
  10. --settings MySecret="@Microsoft.KeyVault(SecretUri=$MIKV_SECRET_URI)"
  11. # get config endpoint
  12. export MIKV_CONFIG=$(az webapp show -n $MIKV_NAME -g $MIKV_RG --query id --output tsv)"/config/web"
  13. # save your MIKV_* environment variables for reuse
  14. ./saveenv.sh -y
  15. # configure the Web App to use Azure Container Registry with Managed Identity
  16. echo "ignore the warning message - the next command fixes the warning"
  17. az webapp config container set \
  18. -n $MIKV_NAME \
  19. -g $MIKV_RG \
  20. -r https://$MIKV_NAME.azurecr.io \
  21. -i $MIKV_NAME.azurecr.io/mikv:latest
  22. # use Managed Identity to connect to ACR
  23. az resource update \
  24. --ids $MIKV_CONFIG \
  25. --set properties.acrUseManagedIdentityCreds=true
  26. # start the Web App
  27. az webapp start -g $MIKV_RG -n $MIKV_NAME

Check Endpoints

  1. # this will eventually work, but may take up to a minute
  2. # you may get a 403 error, if so, just run the curl command again
  3. # curl the health check endpoint
  4. curl https://$MIKV_NAME.azurewebsites.net/healthz
  5. # curl the /api/secret endpoint
  6. curl https://$MIKV_NAME.azurewebsites.net/api/secret/MySecret

Clean up

  1. # delete Key Vault
  2. az keyvault delete -g $MIKV_RG -n $MIKV_NAME
  3. # purge Key Vault to permanently delete
  4. # Key Vaults use a "soft delete" by default
  5. az keyvault purge -n $MIKV_NAME
  6. # delete resource group
  7. az group delete -n $MIKV_RG --no-wait

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit Microsoft Contributor License Agreement.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Trademarks

This project may contain trademarks or logos for projects, products, or services.

Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft’s Trademark & Brand Guidelines.

Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship.

Any use of third-party trademarks or logos are subject to those third-party’s policies.