API deployed on Azure and secured by Azure AD. For example, we will create a simple Azure Function that returns weather data.
public static async Task Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
try
{
HttpResponseMessage response;
AuthenticationContext authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/xxxxxxxxx");
ClientCredential clientCredential = new ClientCredential("xxxxx-xxxxx", "xxxxxx");
AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync("xxxx-xxxxx-xxxxx", clientCredential).Result;
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
//var content = new StringContent(body, Encoding.UTF8, "application/json");
response = httpClient.GetAsync("https://ad-authentication-poc-api.azurewebsites.net/weatherforecast").Result;
}
return response != null
? (ActionResult)new OkObjectResult($"{response.Content.ReadAsStringAsync().Result}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
catch (Exception ex)
{
return new BadRequestObjectResult(ex.Message);
}
}
Try to call the Azure Function from Postman you will receive a message with a 401 Unauthorized error code.
This is because we didn’t pass an Authentication header with a valid bearer token. As we are using AzureAD, we are supporting OAuth2.0 authentication
So far, so good. But what are the parameters that we should pass to Postman to retrieve a token? First, we will use the Authorization Code grant type. When you select this grant type on Postman, you will see that the following parameters are needed:
- Callback URL
- Auth Token URL
- Access Token URL
- Client ID
- Client Secret
To retrieve these information, open the Azure Active Directory select
Client ID
The Client ID parameter is known on Azure AD as the Application ID. Open your registered app and copy the value.
Client Secret
Go to the Keys settings of the Registered App and create a new password. Write down the generated key when saving, you won’t be able to retrieve it later otherwise.
Retrieve the URLs
The Auth Token URL and Access Token URL can be found by clicking on the Endpoints button.
| Postman | Azure AD |
|---|---|
| Auth URL | https://login.microsoftonline.com/[tenant_id]/oauth2/authorize?resource=[application_id] |
| Access Token URL | https://login.microsoftonline.com/[tenant_id]/oauth2/token?resource=[application_id] |
Callback URL :
https://[appservice-name].azurewebsites.net/.auth/login/aad/callback
Retrieve a token
You are now ready to get a new access token.
After clicking on “Request Token” it will create the token and now you can use the token.
- Get link
- X
- Other Apps
- Get link
- X
- Other Apps