NEWS AND BLOGATAHON2021 BLOGS

OAuth 2.0 for Testers

Blogathon2021

OAuth 2.0 for Testers

By Sachin Shinde

Imagine you are a tester having some knowledge about testing APIs either manually or using popular Java-based library for automation i.e. Rest-Assured. Your project manager approaches you and asks you to test and automate OAuth2.0 protocols being implemented by development team. What is the first thing that comes to your mind? Some of you may wonder what is OAuth 2.0, why is it being implemented and most importantly how can I test it. Having realized it is some form of authorization, you will want to know more about its work flow and gather some technical details from your development team in order to write your test cases efficiently. This article will help you to give a quick, concise and practical knowledge about OAuth 2.0 and what it takes to test it using postman and write some automation scripts. This article aims at helping you understand OAuth2.0’s seemingly complex workflow and testing process in a simpler manner. So let’s get started.

What is OAuth 2.0

OAuth 2.0 is the industry-standard protocol for “authorization”. It is neither an API nor a service. It is also not an Authentication protocol. OAuth is a standard that any application can use to provide client application with ‘secure access’. OAuth works over HTTPS and authorizes devices, APIs, servers, and applications with access tokens rather than sharing credentials. Yes, OAuth 2.0 uses Access Tokens! Access token represents authorization that help in giving access to resources on behalf of the end user.

Where have I used OAuth2.0 before

A lot of places. OAuth 2.0 exists almost everywhere these days. Do you remember visiting or registering at centralized hotel booking websites such as ‘Booking.com’, flight booking websites like ‘Skyscanner’, professional networking sites ‘LinkedIn’, some of great learning portals such as ‘Udemy’ or ‘Coursera’? If your answer is ‘Yes’ then you may have used this authorization mechanism but with-out realizing what it is called. Do you recall seeing a dialog shown below? That’s what I am talking about. This is an application asking if it can access data on your behalf.

                                                                     

Why use OAuth 2.0

There are many advantages of using OAuth2.0. First of all, they reduce complexity. You can mandate the authentication process to a third party that you trust, and never worry about user authenticity validation. Secondly, there is no need to store user credentials on company server. Why worry about loss of the sensitive data such as email or password and pay hefty penalty? Rather simply let the authorization server take care of it.

Often it is thought that OAuth shares user credentials between applications but this is not true. In fact, userid or password is never shared from authorization server instead it uses authorization tokens to prove an identity between consumers and service providers.

Understanding workflow of OAuth 2.0

 Let’s say you are developing an application that want to authenticate and login external users via their google account. So in this case, your application becomes a client for which google will assign a unique client id and client secret. You as a client must register your application with google in order to receive them. While registering you will also want to provide a callback URL so that users will redirected that URL upon successful authentication.

OAuth consists of 4 actors in the process of access delegation:

  • Resource Owner (a system or user that owns private resources like email, photos etc.)
  • Client (usually an application that wants to access these resources)
  • Authorization Server (This server receives requests from the Client for Access Tokens and issues them upon successful authentication and consent by the Resource Owner.)
  • Resource Server (who stores user’s private resources and shares them with authorized clients).

While using OAuth2, the client (mobile app, desktop app or website) requests authorization from Authorization Server providing client_id and client_secret as identification. Authorization server authenticates the client. After a user successfully authorizes an application, the authorization server will redirect the user back to the application with either an authorization code or access token in the URL. Using the ‘access_token’ client then requests access to the resource from the resource server as shown the following diagram.

Authorization server may not directly return an Access Token, for better security, sometimes an Authorization Code may be returned, which is then exchanged for an Access Token. In addition, the Authorization server may also issue a Refresh Token with the Access Token. Refresh token usually have longer expiry time than access tokens.

Testing OAuth 2.0 manually using POSTMAN

Let’s take a real world example of an API test where as a tester you have to validate existence of an image file on users Imgur account. Imgur is an online image sharing community. The Imgur API uses OAuth 2.0 for authentication. It contains four steps: registration, authorization, making the request, and getting new access tokens after the initial one has expired. Note that for this test we are going to use ‘Authorization Code’ grant type and assume that an image is already added by the user.

Imgur has already exposed an API to access images for outside world. The end point is https://api.imgur.com/3/account/me/images

As a first step one needs client id and client secret for your application. You can get them by filling up this simple form https://api.imgur.com/oauth2/addclient

Now let’s create a GET method API under new collection in postman with above end point and hit the request. You will initially get 401 unauthorized status code. The reason being we have not provided any authorization to the end point.

In order to provide authorization lets add an account and create oAuth 2 authorization token with following details.

  • Callback URL: {same URL that you used during creating client_id and secret} https://www.getpostman.com/oauth/callback
  • Auth URL: https://api.imgur.com/oauth2/authorizeAccess Token URL: https://api.imgur.com/oauth2/token
  • Client ID: {obtained when you subscribe your app at Imgur service}
  • Client Secret: {obtained when you subscribe your app at Imgur service}
  • Grant Type: Authorization CodeType: OAuth 2.0
  • Token Name: Imgur Sample Token

Click ‘Get New Access Token’ button. It will open a postman window where you enter your registered user credentials on Imgur. Now click Allow button.

You will see a message saying Authentication Complete. Your access token along with refresh token will be visible in the postman account. Simply add this access token to your account.

Go back to your previous GET request API and select the ‘Imgur Sample Token’ we created above.

That’s it. Click ‘Send’ and you will get the 200 OK response and you can see the details of the image file in the response body.

Congratulations you have successfully tested authorization using oAuth 2.0.

 Writing automated scripts for OAuth 2.0

Scripting the end to end test can be little complicated. In the above example, postman tool took care of constructing the required web URL automatically which eventually allowed us to authenticate on Imgur site by entering valid user credential. If you are using any automation library like RestAssured you will need to construct your URL by gathering required parameters for the login UI page. RestAssured itself cannot launch the webpage on any browser. Here you need some additional tools like selenium to take care of UI automation. Selenium can be easily integrated with RestAssured framework under one project which makes our job easier.

First of all, let’s begin by writing the code to launch the web URL. The Authorization URL can be easily constructed using the Auth end point specified on the Imgur API documentation site. You simply need to add the required parameters mentioned on the API contract such as response type, client_id and redirect_uri, etc. Here is how it looks like

https://api.imgur.com/oauth2/authorize?response_type=code&state=&client_id=64c###a5ae46&scope=&redirect_uri=https%3A%2F%2Fwww.getpostman.com%2Foauth%2Fcallback

 Now you can start automating script by creating maven project and add RestAssured and Selenium dependencies. Your code to handle the web browser looks like this. It will launch the chrome browser, open the constructed webpage and pass user credentials.

After authentication, it will then capture the code value rendered in the browser and store in a variable.

Once we get the code value, we can start automating our first end point i.e. token end point. We can pass the code captured above as one of the mandatory body parameters to the POST request.

Create a JsonPath object and extract the needed response as string.

Congratulations! You have successfully received the ‘access_token’. In your final piece of program, you can hit the GET request for images. The request will use this access_token as one of its mandatory header parameters.

You have reached the end of your automation test. Above code will perform validation on the images end point and ensure that response contains the image details uploaded by the user initially. Isn’t testing fun?  

Summary

Among the various grant types, the Authorization Code grant type is probably the most common of the OAuth 2.0 grant types that you’ll encounter as it is widely used with traditional web app. Testing OAuth may seem little complex as you begin however it is very simple once you have written your first test. It is always a good practice to start writing your test using postman or SOAP UI to get familiarized with APIs before you start automating them. Remember, reading API documentation a.k.a. API contract is crucial whether you are testing via postman or automation scripts. So ask for it before you begin your testing. If it does not exist for your project get the needed details from developers. 

 

About the Author

Sachin Shinde is an experienced test engineer. He has worked on a wide variety of products including insurance, health, retail energy, credit risk and banking. Sachin is self-driven and highly motivated in his work. Sachin enjoys writing technical articles, blogs. He is an aspiring speaker at London Java Community (LJC) and a certified scrum master. 

Leave a Comment