Skip to main content

Test Azure AD secured API with Postman


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. 
PostmanAzure AD
Auth URLhttps://login.microsoftonline.com/[tenant_id]/oauth2/authorize?resource=[application_id]
Access Token URLhttps://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. 

Popular posts from this blog

Get Documents Signed Using Adobe Sign API in C#

Electronic signatures have revolutionized the way businesses handle document workflows. Instead of dealing with cumbersome paper-based processes, electronic signatures offer a streamlined and efficient way to obtain legally binding signatures. Adobe Sign API takes this concept to the next level by providing developers with the tools to seamlessly integrate electronic signature capabilities into their applications. In this blog post, we will explore how to use the Adobe Sign API to send documents for signature via email using C#   Understanding Electronic Signatures and Adobe Sign API Electronic signatures, also known as e-signatures, are digital representations of a person's intent to agree to the content of a document. They hold the same legal weight as traditional ink signatures but offer the advantage of speed and convenience. Adobe Sign API allows developers to programmatically incorporate e-signatures into their applications, automating the signature process and enhancing the ...

Working with RabbitMQ using C#

RabbitMQ Topology A Queue  that works on the basis of FIFO (first in first out).  A Publisher is the component that generates some data that is pushed to the queue.  Installation Install the correct version of Erlang based on the operating system you are using. Download and install RabbitMQ server . Now  install the RabbitMQ .Net client from NuGet Package Manager. Sample Codes using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Text; using System.Threading; namespace PracticeRabbitMQ {     class Program     {         static void Main()         {             SendMessage("MessageID", "{MessageID: 1, MessageBody: 'Sample Message' }");             ReceiveMessage("MessageID");             Console.ReadLine();         }   ...