API Testing – Test your OAuth2 secured API using DHC

API Testing – Test your OAuth2 secured API using DHC

With this post you will discover how to test an API secured with OAuth2 resource owner password flow.

Going into this post we assume that you understand the concepts of OAuth2. For more information about it, please refer to https://tools.ietf.org/html/rfc6749.

  • Resource owner password flow is a two-legged approach that will require two steps:
  • A first request will be sent with credentials to the authorization server in order to get the access token;

Then a request can be sent to the protected resource using the access token in order to retrieve data. In this demo, we will rely on brentertainment.com OAuth2.0 demo application (http://brentertainment.com/oauth2/).

1- Retrieve the access token

First you have to create a POST request to the OAuth2.0 server that retrieves the API token.



Note that when changing payload type to form, the corresponding Content-Type header is automatically added to the request.

  • Add the following key/value pairs to the form (with the + button under BODY):
  • grant_type: password
  • client_id: demoapp
  • client_secret: demopass
  • username: demouser
  • password: testpass
  • To ensure we get a valid response and a token, we will add the following assertions to the request:
  • Status code equals 200
  • access_token exists in the response body
  • Click Send, you should then get a "200 OK" response containing the access token:
  • Save your request in a new project and a new scenario (click Save then in the popup, create a new project and a new scenario with the Create button).

2- Use the access token

We will now send a GET request on the resource using the access token retrieved with the first request:

  • Enter the URL of the resource (http://brentertainment.com/oauth2/lockdin/resource).
  • Select GET as a method.
  • Add an Authorization header, set its value to {<YOUR_DHC_PROJECT_NAME>.<YOUR_SCENARIO_NAME>.<1ST_REQUEST_NAME>.response.body.access_token}. This way DHC will retrieve the token value from the first request and set it to the header of the current request.
  • Add an assertion to check that the response status code is 200.
  • Save the request in the same project and scenario than the first one.
  • Click Send to test it.

3- Run these requests as a scenario

  • From your repository, on the left pane, click on the "eye" icon that displays on mouseover for scenarios.
  • This displays the scenario's overview.
  • Clicking on the Run Scenario button will successively send the two requests in one click.
img8Import the following file into your DHC plugin to find the sample corresponding to this article: OAuth2-demo.json.CTA_free trial_3