Automating OAuth2.0 Postman
Since the start of my new role, I've toying with the idea of how I could automate the process of authentication without having to login to our admin dashboard to obtain the Bearer Token copy the value paste it into Postman. It took me almost 24 hours of my spare time researching, with my best friend google for answers and trying out stackoverflow recommendations.
Having used both Insomnia and Postman for awhile, I chose to stick with Postman as I was more familiar with the interface and it had all the features that I would use. Until I stumbled upon, trying to get Google OAuth2 working in my local/production environment.
It could be that I lacked the necessary experience in using, as I never really explored it really in-depth until recently. Postman has a big limitation in terms of generating OAuth2 tokens which I noticed, even though you are able to successfully authenticate and get back the token object. They do not allow you to select which token should be used, in my scenario I required the
id_token whereas Postman only allows
Insomnia on the other hand, I had no problems with OAuth2 and it was so lightweight that I couldn't get use to the interface especially the organisation of the documentations and the tabs. If I had more time I would probably switch to Insomnia if not for the time constraints.
After spending time to research how to automate the authentication process. I discovered that, these solutions didn't work.
This is because, the Postman dev team didn't seem to care about this ticket at all since 2014. I first traced the reason from this community thread. At the latest post, dated 26 Feb 2021. It highlighted that this issue was brought as early as 7 years ago, referring to the latest Postman Github Issues. I guess it was just buried by the tons of issues posted.
Since there was no
option to select whether to use the
id_token from the interface. The only solution is to create a pre-request script.
Taking reference from these examples, I re-created my own script to suit my needs because i could understand it better in my own way.
There are three things you need to setup,
First setup the environment variables. I chose to create them under Globals because its the only Collection I have currently.
You will need 6 variables,
- accessKey - obtained from your google cloud project credentials you can create an API Key.
- refreshToken - obtained by calling - https://oauth2.googleapis.com/token
- grant_type - reference to https://developers.google.com/android-publisher/authorization in my case i'm using "refresh_token"
- accessURL - the base URL for google API https://securetoken.googleapis.com/v1/token
- access_token - its where the script will place the id_token
- accessTokenExpiry - its where the script will place the timestamp of the expiry of the token
Second using this code snippet paste it into your Postman Collection > pre-request script
Third run your API !