Pre-request script to automate authorization code grant type

May i know outline or any examples about pre-request script to capture access token or bearer token when we have below information for “Authorization Code” grant type.
BaseURL
ClientId
ClientSecret
AuthURL
AccessTokenURL
redirect URL
Scope

Currently i am able to capture access token using - “Get New Access Token” button which will launch auth URL into browser and after providing username and password information and it will redirect to postman application with access token and which can be used by clicking on “Use token” button.

I want to automate this manual work through automation using script written at “Pre-request Script” editor.

Previously I have already achieved pre-request script to get access token for grant type = client_credentials for one of project requirements, but now would need help or idea to automate capturing access token for grant type = authorization_code.

Can any one please guide me on the same.

hi @lunar-module-cosmo10 , I am also looking for the same answer. Can someone please post an answer in this thread so that I also get answer for the same.

1 Like

Have you search the world wide web for this?

Have a look at the following.

spring boot - How to get access token via Postman with Authorization Code Grant Type - Stack Overflow

It looks like you need to add the Postman redirect URI to your application as an additional redirect url.

There are a ton of other hits on the same topic.

@michaelderekjones - Thanks for your reply!

I have already searched WWW and also went through most of different articles, but didn’t got any solution related to pre-request script.

Most of articles tells about how to configure in authorization tab for Oauth2.0 authorization for grant type = authorization_code, but I am looking for solution as a script which will replace manual part of clicking on “Get New Access Token” post configuring information in authorization tab at collection/folder/API test step level.

Any help/guidance on the part which i am looking, would be much appreciated.

The link I posted advises to add the Postman redirect URI to your application as an additional redirect url. Log in manually, see from the logs what Postman redirects to, and then add that to your application.

Have you tried this? You also haven’t said what you have tried, and what the results have been.

As far as I can tell, this hopefully should bypass the need to enter this details into the browser.

I don’t have an application to test this on, so it will be trial and error.

Thank you for your reply!

As per link posted by you - i went through link but it says to configure or add redirect_uri additionally to keycloak. As per my understanding - Keycloak is another application or tool. I just want to use only post man application and its features and in my application or project requirement we don’t want to increase dependency on any other additional applications/tools.

The example was using an application called Keycloak but the situation is the same.

You need to add the redirect URI to your application.

If you want to automate using the authentication type of authorisation code without using the browser, then you need to add the Postman redirect URI or you will have to manually authenticate using the browser. Your choice really.

I have tried both options by checking option - “Authorize using browser” and also without checking this option - providing valid redirect URL, it still shows postman prompt (as attached) to login with valid credentials to get authorize my application.

Also, I am already able to capture access token manually and also didn’t got any help from postman logs


.
Appreciate your replies on this post and helping me out here.

But I am still looking for a solution at script end (used as a pre-request script) which in turn will replace manual intervention to capture access token and use it in postman application.

As far as I can tell, it should be possible to do this with a script.

I can’t test this, so I can’t really tell you what options need to be set.

You need to add the Postman redirect URL to your app, which in theory should bypass the browser because the Postman client would then be the browser. Not really 100% on how this works, just that from reading a different posts it would appear that some users have this working.

Did you find a solution? I am looking for the same thing.

Hi,
No, i am still looking/searching for solution.

Hello All,
Can any one please point me into right direction, i am still looking for answer for my doubt/query.

Hey @lunar-module-cosmo10 !

So automating this workflow can be a bit tricky because it typically requires user interaction to provide consent, however if your OAuth provider has a way to bypass the user consent for trusted applications, you can attempt to automate this within the pre-request script section.

Here’s a rough outline of steps:

  1. Generate an auth code
pm.sendRequest({
    url: '{{AuthURL}}?client_id={{ClientId}}&redirect_uri={{redirect URL}}&scope={{Scope}}&response_type=code',
    method: 'GET'
}, function (err, res) {
    var authCode = /* Parse the auth code from the response or the redirect URL. This part depends on your OAuth2.0 provider's implementation. */;
    pm.globals.set('authCode', authCode);
});
  1. Use the auth code to get an access token
pm.sendRequest({
    url: '{{AccessTokenURL}}',
    method: 'POST',
    header: 'Content-Type: application/x-www-form-urlencoded',
    body: {
        mode: 'urlencoded',
        urlencoded: [
            { key: "client_id", value: "{{ClientId}}", disabled: false },
            { key: "client_secret", value: "{{ClientSecret}}", disabled: false },
            { key: "grant_type", value: "authorization_code", disabled: false },
            { key: "redirect_uri", value: "{{redirect URL}}", disabled: false },
            { key: "code", value: pm.globals.get('authCode'), disabled: false }
        ]
    }
}, function (err, res) {
    var jsonData = res.json();
    if(jsonData.access_token) {
        pm.globals.set('accessToken', jsonData.access_token);
    }
});
  1. Then include the access token in your request headers as a variable
Authorization: Bearer {{accessToken}}

Remember:

  • This approach assumes that user consent can be bypassed. If the user has to provide consent, it can’t be fully automated within Postman.
  • Always ensure that ClientSecret is kept secure. Ideally, it shouldn’t be stored or transmitted unless it’s absolutely necessary.
  • This script might need tweaks depending on your OAuth2.0 provider’s specific implementation.

@kevinc-postman - Thanks, for reply with information.

Got to know that, we can only achieve via script inside Postman IDE only when user interaction to provide consent is bypassed. In my case, it asks user to provide authentication information (like username and password) to get auth code.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.