Using Postman Automation to Test API Endpoints Protected by Okta’s PKCE Flow

Postman is a great tool for testing our APIs and streamlining backend development. One of the big hurdles, however, is testing API endpoints that are protected. There are some imperfect workarounds that require us to manually enter our credentials each…


This content originally appeared on DEV Community and was authored by Andy T. Tran

Postman is a great tool for testing our APIs and streamlining backend development. One of the big hurdles, however, is testing API endpoints that are protected. There are some imperfect workarounds that require us to manually enter our credentials each time we need to retrieve an access token. But through painstaking trial and error, I’ve put together a solution to automate the Postman login process with the click of a button! In this blog, I will go over step-by-step how you can create the same automated Postman login setup. The following requests are based on the Okta platform and Okta’s authorization code flow with PKCE documentation.


Collection and Environment Variables Setup

  1. Create a collection under Collections > + > Create New Collection. We’ll name this collection “Okta Login,” but this can be named anything you like. The collection will allow us to use runners to run all our requests at once.

  2. Setup our environment variables based on Okta’s authorization code flow docs.

Postman Environment Variables Screenshot

  • The email and password are the user credentials.
  • The oktaUrl (Okta domain) and oktaClientId (Client ID) can be found within the general settings of your Okta app.
  • The redirectUri must match one of the URIs that you have approved for your Okta application. These redirect URI value(s) can be found under the Login redirect URIs field in your Okta Applications settings (screenshot below). If your application doesn’t already have a redirect URI, you can set it up with a http://localhost:3000. As part of the authorization code flow, users are redirected back to your client application via the redirectUri after logging in with Okta. In our case, we won’t be redirecting anywhere, but the redirectUri is required as a parameter of the request.

Okta App Settings Screenshot

  • The codeChallenge and codeVerifier values can be generated here: https://tonyxu-io.github.io/pkce-generator/. The code challenge and code verifier values are used in the Proof Key of Code Exchange (PKCE) flow. You can find more details on Okta’s implementation here.
  • The authServer is set as default unless you have created a custom auth server.
  • The sessionToken, authorizationCode, and accessToken can be left blank, as we will programatically fill in these values from our requests.

We will tidy things up by using Postman variables. We can access these environment variables by adding two curly braces around our environment variable name. For example, instead of typing “http://localhost:3000,” we can just use {{redirectUri}}. This helps keep our variables consistent and easily managed/updated.

Creating Requests

1.First, we will create a POST request to your Okta domain + /api/v1/authn. Since we have this value set in our environment variable, we can just use {{oktaUrl}}/api/v1/authn in the URL. In the JSON body of the request, we will send our username and password.

Auth Flow Step 1 Screenshot

This is the authentication piece of the flow. Okta will return all the user info, including the session token. Since we want to automate this process, we will create a script so that this session token is saved into an environment variable. We can add scripts within the Tests section. Add the script below to the Tests section of this first request.

const response = JSON.parse(responseBody);

pm.environment.set("sessionToken", response.sessionToken);

pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

pm.test("Response returns a session token", function () {
    pm.expect(response).to.have.property("sessionToken");
});

2.Next, create a GET request to {{oktaUrl}}/oauth2/default/v1/authorize. We will need to exchange that session token for an authorization code, which will involve sending a few values as query parameters:

  • client_id={{oktaClientId}}
  • scope=openid
  • redirect_uri={{redirectUri}}
  • response_type=code
  • state=state
  • sessionToken={{sessionToken}}
  • code_challenge={{codeChallenge}}

For more details on what the parameters are used for, you can check out the docs here.

Auth Flow Step 2 Screenshot

We will save the authorization code from Okta's response to this request as an environment variable. Add the following script to the tests section of this second request:

const responseUrl = postman.getResponseHeader("Location");
const authorizationCode = responseUrl ? responseUrl.match(/code=([^&]*)/)[1] : null;

pm.environment.set("authorizationCode", authorizationCode);

pm.test("Status code is 302", function () {
    pm.response.to.have.status(302);
})

pm.test("Response returns an authorization code", function () {
    pm.expect(authorizationCode).not.equal(null);
});

3.Last, we will create a POST request to {{oktaUrl}}/oauth2/{{authServer}}/v1/token?state=state to exchange the authorization code for our access token. We will need to send this in a x-www-form-urlencoded format with the following query parameters:

  • grant_type=authorization_code
  • redirect_uri={{redirectUri}}
  • code={{authorizationCode}}
  • code_verifier={{codeVerifier}}
  • client_id={{oktaClientId}}

Auth Flow Step 3 Screenshot

We will finally save the access token that we need from Okta's response to this request as an environment variable. Add the the following script to the tests section of this third request:

const response = JSON.parse(responseBody);

pm.environment.set("accessToken", response.access_token);

pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

pm.test("Response returns an access token", function () {
    pm.expect(response).to.have.property("access_token");
});

Running Our Collection and Final Setup

Now that we have everything setup, we can simply run our collection using Postman runners. To do this, double click on the Okta Login collection. You will see the Run button, which opens up the Runner tab.

Okta Login Collection Screenshot

We then can click on Run Okta Login and voila! We have our access token saved in our environment variables, and we can now use it to hit protected endpoints on our server.

Postman Runner

Access Token Usage

Accessing our protected routes is possible now that we have our access token. In the authorization tab of your request, select Bearer Token from the drop-down menu. Add {{accessToken}} as the value for Token and presto… we can now make API requests as if we were logged in as a user!

Access Token Usage

Conclusion

Using Postman collection runners to get our Okta access token makes API testing and backend development much more streamlined. Since we can programmatically get our access token, this collection can also be useful in creating full regression tests to ensure that all endpoints (including the protected ones) are working as expected. This setup can also be tweaked to be used with other identity providers that utilize the authorization code flow, such as Auth0, AWS Cognito, etc. If you have any questions or improvements, let me know in the comments below!


This content originally appeared on DEV Community and was authored by Andy T. Tran


Print Share Comment Cite Upload Translate Updates
APA

Andy T. Tran | Sciencx (2021-06-01T15:03:43+00:00) Using Postman Automation to Test API Endpoints Protected by Okta’s PKCE Flow. Retrieved from https://www.scien.cx/2021/06/01/using-postman-automation-to-test-api-endpoints-protected-by-oktas-pkce-flow/

MLA
" » Using Postman Automation to Test API Endpoints Protected by Okta’s PKCE Flow." Andy T. Tran | Sciencx - Tuesday June 1, 2021, https://www.scien.cx/2021/06/01/using-postman-automation-to-test-api-endpoints-protected-by-oktas-pkce-flow/
HARVARD
Andy T. Tran | Sciencx Tuesday June 1, 2021 » Using Postman Automation to Test API Endpoints Protected by Okta’s PKCE Flow., viewed ,<https://www.scien.cx/2021/06/01/using-postman-automation-to-test-api-endpoints-protected-by-oktas-pkce-flow/>
VANCOUVER
Andy T. Tran | Sciencx - » Using Postman Automation to Test API Endpoints Protected by Okta’s PKCE Flow. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/06/01/using-postman-automation-to-test-api-endpoints-protected-by-oktas-pkce-flow/
CHICAGO
" » Using Postman Automation to Test API Endpoints Protected by Okta’s PKCE Flow." Andy T. Tran | Sciencx - Accessed . https://www.scien.cx/2021/06/01/using-postman-automation-to-test-api-endpoints-protected-by-oktas-pkce-flow/
IEEE
" » Using Postman Automation to Test API Endpoints Protected by Okta’s PKCE Flow." Andy T. Tran | Sciencx [Online]. Available: https://www.scien.cx/2021/06/01/using-postman-automation-to-test-api-endpoints-protected-by-oktas-pkce-flow/. [Accessed: ]
rf:citation
» Using Postman Automation to Test API Endpoints Protected by Okta’s PKCE Flow | Andy T. Tran | Sciencx | https://www.scien.cx/2021/06/01/using-postman-automation-to-test-api-endpoints-protected-by-oktas-pkce-flow/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.