Technical Insights: Azure, .NET, Dynamics 365 & EV Charging Architecture

Tag: Azure

Simplifying API Testing in Postman: Auto-refresh OAuth Tokens with Pre-request Scripts

Introduction:

Welcome to a quick guide on enhancing your API testing workflow in Postman! If you frequently work with APIs that require OAuth tokens, you know the hassle of manually refreshing tokens. This blog post will show you how to automate this process using Pre-request scripts in Postman.

What You Need:

  • Postman installed on your system.
  • API credentials (Client ID, Client Secret) for the OAuth token endpoint.

Step 1: Setting Up Your Environment

  • Open Postman and select your workspace.
  • Go to the ‘Environments’ tab and create a new environment (e.g., “MyAPIEnvironment”).
  • Add variables like accessToken, clientId, clientSecret, and tokenUrl.

Step 2: Creating the Pre-request Script

  • Go to the ‘Pre-request Scripts’ tab in your request or collection.
  • Add the following JavaScript code:
if (!pm.environment.get('accessToken') || pm.environment.get('isTokenExpired')) {
    const getTokenRequest = {
        url: pm.environment.get('tokenUrl'),
        method: 'POST',
        header: 'Content-Type:application/x-www-form-urlencoded',
        body: {
            mode: 'urlencoded',
            urlencoded: [
                { key: 'client_id', value: pm.environment.get('clientId') },
                { key: 'client_secret', value: pm.environment.get('clientSecret') },
                { key: 'grant_type', value: 'client_credentials' }
            ]
        }
    };

    pm.sendRequest(getTokenRequest, (err, res) => {
        if (err) {
            console.log(err);
        } else {
            const jsonResponse = res.json();
            pm.environment.set('accessToken', jsonResponse.access_token);
            pm.environment.set('isTokenExpired', false);
        }
    });
}

Step 3: Using the Access Token in Your Requests

  • In the ‘Authorization’ tab of your API request, select ‘Bearer Token’ as the type.
  • For the token, use the {{accessToken}} variable.

Step 4: Testing and Verification

  • Send your API request.
  • The Pre-request script should automatically refresh the token if it’s not set or expired.
  • Check the Postman Console to debug or verify the token refresh process.

Conclusion: Automating token refresh in Postman saves time and reduces the error-prone process of manual token updates. With this simple Pre-request script, your OAuth token management becomes seamless, letting you focus more on testing and less on token management.

Further Reading:

Read and remove scheduled message in Azure Service Bus

Ever wondered on how you can remove the scheduled message in Service bus topic or queue? We had a bug where one of our service keep queuing the messages while its not meant to be queued and we deployed the fix but in order to test the fix we need to make sure there are no messages are being scheduled therefore we need to remove all scheduled messages to test if the fix is working

At the same time you can also use the same code to check your messages if it is all being scheduled properly based on your logic

I was expecting the service bus explorer on azure portal allow us to peek into this scheduled messages but unfortunately it doesn’t have this feature

for service bus topic you can use below code

class Program
    {

        // Connection String for the namespace can be obtained from the Azure portal under the
        // 'Shared Access policies' section.
        const string ServiceBusConnectionString = "[Servicebus connection string with entity path]";
        static ITopicClient topicClient;
        static IMessageReceiver messageReceiver;

        static void Main(string[] args)

        {
            MainAsync().GetAwaiter().GetResult();
        }

        static async Task MainAsync()
        {
            var sbConnStringBuilder = new ServiceBusConnectionStringBuilder(ServiceBusConnectionString);
            topicClient = new TopicClient(sbConnStringBuilder);
            Console.WriteLine("======================================================");
            Console.WriteLine("Press any key to exit..");
            Console.WriteLine("======================================================");

            messageReceiver = new MessageReceiver(sbConnStringBuilder);

            Message message = await messageReceiver.PeekAsync();

            // Message with property ScheduledEnqueueTimeUtc not null means it is a scheduled message

            while (message != null)
            {
                if (message != null && message.ScheduledEnqueueTimeUtc != null)
                {
                    // Remove the scheduled message
                    await topicClient.CancelScheduledMessageAsync(message.SystemProperties.SequenceNumber);
                }
                message = await messageReceiver.PeekAsync();
            }

            Console.ReadKey();
            await topicClient.CloseAsync();
        }

    }

For the service bus queue you can use code below

class Program
    {

        // Connection String for the namespace can be obtained from the Azure portal under the
        // 'Shared Access policies' section.
        const string ServiceBusConnectionString = "[Servicebus connection string with entity path]";
        static IQueueClient queueClient;
        static IMessageReceiver messageReceiver;

        static void Main(string[] args)

        {
            MainAsync().GetAwaiter().GetResult();
        }

        static async Task MainAsync()
        {
            var sbConnStringBuilder = new ServiceBusConnectionStringBuilder(ServiceBusConnectionString);
            queueClient = new QueueClient(sbConnStringBuilder);
            Console.WriteLine("======================================================");
            Console.WriteLine("Press any key to exit..");
            Console.WriteLine("======================================================");

            messageReceiver = new MessageReceiver(sbConnStringBuilder);

            Message message = await messageReceiver.PeekAsync();

            // Message with property ScheduledEnqueueTimeUtc not null means it is a scheduled message

            while (message != null)
            {
                if (message != null && message.ScheduledEnqueueTimeUtc != null)
                {
                    // Remove the scheduled message
                    await queueClient.CancelScheduledMessageAsync(message.SystemProperties.SequenceNumber);
                }
                message = await messageReceiver.PeekAsync();
            }

            Console.ReadKey();
            await queueClient.CloseAsync();
        }

Powered by WordPress & Theme by Anders Norén