Walkthrough: how to retrieve an Azure Key Vault secret from an Azure Function App using client credentials flow with certificate

Introduction:

This post builds on the information from the previous post and I will assume that you already have an Azure Key Vault, an AAD Application registration, and a certificate file. We will cover the following steps in this blog in order to use a certificate from an Azure Function App:

  1. Create an Azure Function App
  2. Upload the certificate to the Function App
  3. Configure the Function App to load certificate file
  4. Create an Azure Function to consume the certificate

Create an Azure Function App

From the Azure Market Place in the Azure portal, create an Azure Function App. The Hosting Plan can either be Consumption Plan or App Service Plan.

Upload the certificate to the Azure Function App

Go to the Function App resource we just created => click on Platform features tab => click on SSL link

From the SSL blade => click on Private Certificates (.pfx) tab => click the Upload Certificate link

Go through the Certificate Upload wizard to provide a pfx file and password. Once the upload is complete, the certificate info should appear under the Private Certificate section

Configure the Function App to load the certificate

From the Function App blade, click on the Application settings link under the Platform features tab

Under Application settings section, add a new setting called WEBSITE_LOAD_CERTIFICATES and set the value to be the certificate thumbprint. Click on Save button to save the new setting

Create an Azure Function

From Visual Studio 2017, create a new Azure Functions project. If you don’t see the “Azure Functions” template, you may need to install “Azure Functions and Web Jobs Tools” extension. See https://docs.microsoft.com/en-us/azure/azure-functions/functions-develop-vs for more info.

For the Function trigger, I just choose Timer trigger for the purpose of this blog. You an choose any trigger you like. Trigger is just a mean to invoke an Azure Function. If you have a storage account then go ahead and configure the storage account for the Function under Storage Account setting. The schedule setting uses CRON expression to define a timer schedule for the Function App. The prepopulated expression 0 */5 * * * * means that the Function is invoked every 5 minutes.

Now we need to write the code for this Function:

  1. Install the following Nuget packages from the Package Manager Console:

Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory

Install-Package Microsoft.Azure.KeyVault

  1. Replace the code in Function1.cs with the following code:

[gist id=”069082b4a4a2df7b0e3f9ef4ccf4498b” file=”Function1.cs”]

  1. Build and publish this Azure Function to our Azure Function App by right-click on the Project name and select “Publish…”

    Note: If you have not done this already, make sure you log into Visual Studio with your Azure AD account.


Select the target to be our existing Azure Function App and click “Publish”

Select the right Azure Function App under the right Resource Group and click OK to publish

Once the publishing is finished, we should see our Function 1 appearing in the Azure portal. You can click on the “Run” button to see the output in the Logs section at the bottom.

References

https://docs.microsoft.com/en-us/azure/azure-functions/functions-develop-vs

https://azure.microsoft.com/en-us/blog/using-certificates-in-azure-websites-applications/

Walkthrough: how to retrieve an Azure Key Vault secret from a console app using client credentials flow with certificate

Introduction

This is a code walkthrough to show you how to create a .Net console application to authenticate to Azure Active Directory using OAuth2 Client Credentials flow to get an access token to Azure Key Vault. It then uses the access token to call Azure Key Vault to get a secret. The following steps will be performed in this post:

  1. Create an Azure Key Vault
  2. Create a new self-signed certificate to use in client credentials flow
  3. Create a new Application Registration
  4. Create a new console app to retrieve a secret from Azure Key Vault

Create an Azure Key Vault

You can create an Azure Key Vault from the Azure portal if you don’t have one already. Refer to https://docs.microsoft.com/en-us/azure/key-vault/key-vault-get-started for more info. I use the Powershell script below to create a new Azure Key Vault and then set a new secret.

[gist id=”f712488ddd72ab9eed7c6b0e2115ce61″ file=”CreateKeyVault.ps1″]

The above script creates an Azure Key Vault called BlogKV123 with a secret called SQLPassword:

Create a new self-signed certificate

I use the Powershell script below to create a new exportable self-signed certificate. See https://docs.microsoft.com/en-us/azure/key-vault/key-vault-use-from-web-application for more info.

[gist id=”e5f4671e35a97f3b3e8a579b9a2c05b9″ file=”CreateSelfSignedCert.ps1″]

Create a new Application Registration

We need to create a new Application Registration in the Azure Active Directory’s App Registration blade and then upload the certificate cer file created above to the Keys section of the Application. In addition, we also need to give our Application (really its Service Principal) access permission to the Azure Key Vault to read its secret info. I use the following Powershell script from https://docs.microsoft.com/en-us/azure/key-vault/key-vault-use-from-web-application to do this.. Take note of the certificate thumbprint output below as you will need it later for the application code.

[gist id=”c5a8c49ed9e831e98925e25cf3b2ffd7″ file=”CreateAADAppwithKeyVault.ps1″]

The script above should create a “Web app / API” Application type and upload the certificate file to the Application in the Keys => Public Keys section as in the screen shot below.  The thumbprint info should match the output above in the Powershell console.

Take note of the Application ID and the thumbprint as you will use it in your console app later.

Over in the Azure Key Vault blade, you should see the Service Principal for our Application listed in the Access policies section with all the given secret operation permission

Create a Console Application

  1. From Visual Studio 2017 Create a new .Net console app:

  1. Install the following Nuget packages from the Package Manager Console:

Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory

Install-Package Microsoft.Azure.KeyVault

  1. Replace the code in Program.cs with the following code (Use both the Application ID and the certificate thumbprint from above on line 14 and 15 respectively):

[gist id=”8e986c31c71da41d696ac4d4b175df2a” file=”Program.cs”  ]

  1. Run the application and you should get the output ‘Pa$$w0rd’ printed out.

References:

https://docs.microsoft.com/en-us/azure/key-vault/key-vault-get-started

https://www.rahulpnath.com/blog/authenticating-a-client-application-with-azure-key-vault/

https://docs.microsoft.com/en-us/azure/key-vault/key-vault-use-from-web-application

Testing B2C Resource Owner Password Credentials ( ROPC ) policies using PostMan

Below are the basic steps for using PostMan to test a B2C Resource Owner Password Credentials ( ROPC ) policy. You will need a set of user credentials along with a Application ID of a B2C Native application that will be used to retrieve the token.

Obtain the token endpoint from the B2C ROPC Policy

1. In the portal, locate the B2C blades by searching for B2C, then locate the “Resource Owners Policies” item and click it.

2. In the list of policies to the right, Click the name of the policy.

clip_image002[4]

3. Locate the ROPC Policy URL and click.

clip_image004[4]

4. In the JSON that is displayed in the Brower, make a note of the “token_endpoint” property.

{
“issuer”: https://login.microsoftonline.com/f06c2fe8-709f-4030-85dc-38a4bfd9e82d/v2.0/,
“authorization_endpoint”: https://login.microsoftonline.com/casalaola.onmicrosoft.com/oauth2/v2.0/authorize?p=b2c_1_maxv_b2c_ropc_policy,
     “token_endpoint”: https://login.microsoftonline.com/casalaola.onmicrosoft.com/oauth2/v2.0/token?p=b2c_1_maxv_b2c_ropc_policy,
“jwks_uri”: https://login.microsoftonline.com/casalaola.onmicrosoft.com/discovery/v2.0/keys?p=b2c_1_maxv_b2c_ropc_policy,
“response_modes_supported”: [
“query”,
“fragment”,

“form_post”

],

….<JSON content removed for brevity>

}

In this example the token URL would be:

https://login.microsoftonline.com/casalaola.onmicrosoft.com/oauth2/v2.0/token?p=b2c_1_maxv_b2c_ropc_policy

Obtain the Application ID of the B2C Native application that will be used to request the token.

    1. In the B2C main blade click the Applications menu item.
    2. Then click the target application from the list of applications to the right.

image

3. On the Properties blade of the application. Locate the Application ID and click the clipboard icon clip_image007[4] to its right.
You will need this GUID when you build the PostMan request

clip_image009[6]

In this example the application id would be:

9dd348b1-8f19-49c9-82ee-10e382eddba6

Build the token request using PostMan

1. Start PostMan desktop application. If you need to install PostMan visit the following URL:

https://app.getpostman.com/app/download/win64

2. Click the New button or if you allow the Create New wizard to launch at start up, click Request region.

clip_image011

3. In the SAVE REQUEST box, give the request a name, in this example the name chosen is “B2C ROPC Test Post”. Add a description that makes sense to you.

4. If you have no collections, create “B2C API Testing” collection, you can name the collection whatever you like or add the request to an existing collection.

5. Click the “Create Folder” or select a collection from the folder list.

6. Click the “Save To….” Button.

clip_image013

7. Select “POST” from the operation type drop down.

8. Place the token URL for the application in the “Enter Request URL” edit control. In this example post, the URL would be:
https://login.microsoftonline.com/casalaola.onmicrosoft.com/oauth2/v2.0/token?p=b2c_1_maxv_b2c_ropc_policy

9. Click “Body” section of the request

10. Click the “x-www-form-urlencoded” radio button clip_image014[4].

NOTE:

If you add the key value pairs before clicking the radio button, you will be required to renter the key values pairs once again. Be sure to click the x-www-form-urlencoded radio button first.

11. Add the key value pares from the following table:

Key Value
username UPN Of User you want to request a JWTToken for
password Corresponding Password for the username
grant_type password
scope openid <appId Guid> <other scoping parameters>
client_id <application ID of the app you want to test>
response_type token id_token

The values for this example would be:

Key Value
username zbfp@outlook.com
password (HeartOfGold)
grant_type password
scope openid 9dd348b1-8f19-49c9-82ee-10e382eddba6
client_id 9dd348b1-8f19-49c9-82ee-10e382eddba6
response_type token id_token

The “Headers” tab will be automatically populated.

The post should look similar to the  following:

clip_image016[6]

12. Click the Send clip_image017[4] button.

13. The Status code will be 200 if the request is successful. If there is an error. The body of the request will contain the specific error.

14. The response will contain the token information if successful. You can use a site like http://jwt.ms to decode, both, the access_token and id_token properties.  The following illustration is an example of a successful POST to a B2C ROPC Policy token end point:

image

How to change a display Name of a registered application from another application

Introduction:

This post will show you to change a displayName of a registered web application from another application using client credentials flow with Application Permission

Walk Through steps:

1) In Azure AD’s App Registration portal, create 2 new app registrations called TestAppA and TestAppB. We will use TestAppA to change the display Name of TestAppB. It is not important what permission you configure for TestAppB. For TestAppA make sure you configure Microsoft Graph’s Application.ReadWrite.OwnedBy permission (check the option for “Manage apps that this app creates or owns) under Application Permission and also click on the “Grant Permission” button to provide admin consent to TestAppA

clip_image002

Also note the Application ID for both TestAppA and TestAppB

clip_image004

2) For TestAppA create a new key and note its value:

clip_image006

3) Get the Object ID of TestAppA’s Service Principal from the Enterprise applications blade

clip_image008

4) Use Microsoft Graph Explorer tool to make the TestAppA’s Object ID obtained in step 3 the owner of TestAppB by issuing the following POST request:

POST https://graph.microsoft.com/applications/{id of App2}/owners/$ref
POST Body:
{

“@odata.id”:”https://graph.microsoft.com/v1.0/servicePrincipals/{SP ObjectId of App1}

}

clip_image010

Note: Wait at least 20 minutes to perform the steps below:

5) For demo purposes I am using PostMan in this step to get an access token for TestAppA.

POST request to https://login.microsoftonline.com/<Directory ID>/oauth2/v2.0/token

POST body:

grant_type=client_credentials&scope=https://graph.microsoft.com/.default&client_id=<TestAppA App ID>&client_secret=xxx

clip_image012

6) Use PostMan to issue a PATCH request with an access token obtained above to change TestAppB’s displayName

PATCH https://graph.microsoft.com/beta/applications/<TestAppB App ID>
Body:
{

“displayName”: “new name”

}
clip_image014

Summary:

The steps above demonstrates the concept of how to change an application’s property such as displayName from another application. You can use the same technique to change an application’s other properties. The key here is that in order to change an application’s property, the calling app needs to have Application.ReadWrite.OwnedBy MS Graph permission and it needs to be an owner of the callee app. For demo purposes, this post uses PostMan to get an access token and issues an MS Graph call to change the property. In practice the calling application can use ADAL library to get an access token and make the same MS Graph call.

Query String is not allowed in redirect_uri for Azure AD

Problem:

See update at the end.  This is no longer an issue.

Customer configures the following redirect URLs for his registered application in Azure AD

clip_image001[6]

and issues the following request to authenticate to Azure AD:

GET https://login.microsoftonline.com/<tenant id>/oauth2/authorize?client_id=<app id>&redirect_uri=https%3a%2f%2flocalhost%3a44396%2fbac%2faad%3freqId%3dA123&response_mode=form_post&….

After logging in he is redirected to https://localhost:44396/bac/aad instead of https://localhost:44396/bac/aad?reqId=A123.

The redirected URL does not have anything after the query string.

Root Cause:

The behavior is by design.  This is an Azure AD’s security feature to prevent Covert Redirect attack.

Resolution:

We recommend customer to make use of the ‘state’ parameter instead of using query string to preserve the state of the request.

Update 8/15/2019

https://docs.microsoft.com/en-us/azure/active-directory/fundamentals/whats-new

https://docs.microsoft.com/en-us/azure/active-directory/develop/reference-breaking-changes#redirect-uris-can-now-contain-query-string-parameters

Azure AD now can accept reply URLs with query string.  This can be done by modifying the manifest file in the App Registration portal like the following.  This functionality is currently not available in the UI yet.

“publisherDomain”: “xxx.onmicrosoft.com”,
“replyUrlsWithType”: [
{
“url”: “https://localhost”,
“type”: “Web”
},
     {
          “url”: “https://www.contoso.com/otdsws/login?authhandler=Microsoft+OAuth”,
          “type”: “Web”
     }
],

“requiredResourceAccess”: [
{

..

Update 8/23/2019 – You now can enter reply URL with query string in the App Registration UI

Changing an existing Native Application to a Web App/API to get existing keys

Introduction

 

This article is meant to help get the keys from your native application. We used to show the keys in native applications however we took out that feature because the native application is not meant to have keys/secrets. As a result some people have had keys/secrets with their native applications however they currently still use those keys/secrets. This article is to help those people in order to get access to their keys/secrets or to simply change an existing application from a native application a web api.

 

Note : This is not recommended practice, and this is solely meant for customers who have keys on their native application but can’t get to them anymore; so they need a workaround to get access to the native application Keys

 

Changing a Native Application to a Web API

 

In order to change a Native Application to a web API, first you’ll have to open up the application manifest in the azure portal for your AAD Application that you would like to change. After finding your application press the manifest button shown in the picture below.

 

Please note that this does not work from web API to native application, you can only do it from Native Application to Web API.

 

image

 

image

 

The highlighted field “publicClient” is the field that determines whether an application is a web app/api or native application. When it is true, it is a native application otherwise it is a web app. Once you turn the application into a web app you will be able to see the keys blade.

 

 

image

image

 

As you can see from the two pictures above, the keys blade is not in the native application. But when we change the application to a web app/api we are able to see the keys blade now. This is helpful for users who created keys when it was available for native applications.

 

 

Conclusion

We have now shown how to change a native application to a web API by changing the publicClient field in the application manifest. If there are any more questions regarding this issue feel free to post a comment and we will respond as soon as possible.