OAuth2 authentication in Zerocode
TL;DR Zerocode is an open source lib enables API testing via simple declarative JSON steps — REST, SOAP and DB services. This article is about using zerocode to test a REST API which supports OAuth2 authentication.
Testing the REST API is still a bit of a pain with modern tools like Insomnia, Postman, REST Assured, etc. Zerocode has taken a different approach to solve the fuss involved in the REST API testing. Testing here refers to automation testing. When using zerocode, your REST API automation testing becomes more elegant and straight forward. It is more maintainable and easy to use.
You just need to manual test you REST API once which can be recorded and ran whenever by whoever wants to test the integrity of the REST API. It can also be ran from CI jobs.
I am not going to speak more about zerocode. For more info head to https://github.com/authorjapps/zerocode.
Let’s dive into the topic.
You have a REST API to be tested. But what if your REST API supports only OAuth2 authentication and you want to test it in the same way. It makes sense to test the API as it is in the production so that it behaves similar when testing. Also unlike other authentication methods, OAuth2 is dynamic. The tokens are valid only for a certain amount of time. So it cannot be hard coded instead, it has to dynamically generated.
There is no built-in support for OAuth2 authentication in zerocode. But we are going to exploit the extendability of the zerocode to support OAuth2 authentication. Zerocode can be extended to satisfy your requirements.
It is possible to inject custom(Authorization) header in every request by extending the ‘BasicHttpClient’ and overriding the ‘handleHeaders’ method.
In this method, you can insert anything of your choice.
All you need is to implement the OAuth2 authentication logic in your code. Finally, generate the token from your implementation and inject it into the request header. Sounds cool. But Oauth2 implementation???
We got you covered. There is a working example available in the hello-world-repo. You can copy it and flavor it according to your needs. Because people are good at do things it in their own way.
No library can support all your requirements, but it should be extendable to achieve it. Zerocode was written with this as a principle.