How to automatically set the access token for authenticated requests in Insomnia

This entry was posted on

  • Insomnia
  • testing
  • tutorial
  • security

Problem

The Graphql endpoint for the API is accessible only to authorised users. Although it is required from a security perspective, it makes testing the API through Insomnia a little tedious. What if we could automatically insert the bearer token every time we made a request using Insomnia?

Solution

Let’s start by creating a new environment. Although not entirely necessary, it makes authenticating on different environments easy. Note: You can give the environment better names such as Dev, Staging, Production etc

Creating a new environment
Creating a new environment

Now, let’s add some environment variables specific to that environment

  • baseUrl : The base URL for all the endpoints
  • email: The email used to login
  • password: The password used to login

Adding environment variables
Adding environment variables

Let’s make insomnia use the environment.

Use the environment
Use the environment

Assuming that the endpoint to get the access token is LoginUser add a new post request called GetAccessToken.

Remember the environment variables from earlier. We can use them so that no matter what environment we are on, everything will just work.

Get token
Get token

Let’s add a new Graphql query and try to send the request. We get a 401 Unauthorized error because we haven’t passed in the bearer token.

Graphql request without bearer token
Graphql request without bearer token

To set the bearer token, we can click on the Bearer tab and enter Response ⇒ Body Attribute for the token.

Set the bearer token
Set the bearer token

To edit the tag, click on it.

Edit the tag
Edit the tag

In the Edit Tag screen select Post GetAccessToken for the request

Set the request on the tag screen
Set the request on the tag screen

Set the trigger behaviour to Always so that the request is made every time and you get a new token

Set the trigger behavior
Set the trigger behavior

For the filter, enter $.accessToken.value. The value will be dependent on the response that you get from GetAccessToken. If you have set it up correctly, you should see a token in the Live Preview.

Set the filter
Set the filter

Now, if you try to resend the request, you should get back a 200 OK response.

Send a successful request
Send a successful request

Conclusion

By automatically generating access tokens every time we make a Graphql request, we can easily test our API using Insomnia

More like this

Ankur Sheel © 2021
Connect with me
GithubTwitterLinkedIn