Search code examples
asp.net-web-apiautomated-testsasp.net-web-api2postmannewman

How to develop test-automation using Postman when OAuth 2.0 authorization is required


I have an ASP.NET Web API 2 which is using OAuth 2.0 for authorization. And let's imagine I have a simple Web API method, like:

GET: http://host/api/profiles/user123   (requires OAuth 2.0 token)

So, with Postman, it is easy to test this Web API. I get an OAuth token for user123 from the Web API OAuthAuthorization method and then I use that token in the header of the HTTP request:

GET /api/profiles/user123   HTTP/1.1
Host: {host}
Authorization: Bearer {Token}
Content-Type: application/json
Cache-Control: no-cache

However, if I save my test and run it later (either by Postman itself or by Newman), the token will be expired at that time and it won't work.

How can I make Newman to get a new token automatically for user123 and use it in the HTTP request?

Note: I know how to use Postman's Authentication helpers to ask for a new token. But this scenario doesn't fit the test-automation. In test-automation, I want to remove any human interaction.


Solution

  • It's simple, get your access token at run time and save it into environment variable. Then use it in your next Get request.

    In Get Token request, do this in Tests sections:

    var body = JSON.parse(responseBody);
    pm.environment.set('AccessToken', body.access_token);
    

    In your main Get request, you can use the environment variable in Authorization header:

    Authorization: Bearer {{AccessToken}}
    

    Hope this helps.