How to do Authentication in Rest Assured – Part 10

Authentication in Rest Assured

What we have learned so far?

Part 1 – What is Rest Assured? How to setup Rest Assured?
https://www.onlyfullstack.com/what-is-rest-assured-how-to-setup-rest-assured/

Part 2 – Sample Rest API To Test With Rest Assured
https://www.onlyfullstack.com/sample-rest-api-to-test-with-rest-assured/

Part 3 – How to make a GET Request using Rest Assured – Only Fullstack
https://www.onlyfullstack.com/how-to-send-get-request-in-rest-assured/

Part 4 – How to make a POST Request using Rest Assured – Only Fullstack
https://www.onlyfullstack.com/how-to-send-post-request-in-rest-assured/

Part 5 – How to make a PUT Request using Rest Assured – Only Fullstack
https://www.onlyfullstack.com/how-to-send-put-request-in-rest-assured/

Part 5 – How to make a DELETE Request using Rest Assured – Only Fullstack
https://www.onlyfullstack.com/how-to-send-delete-request-in-rest-assured/

Part 7 – JsonPath and XmlPath in Response Rest Assured – Only Fullstack
https://www.onlyfullstack.com/jsonpath-and-xmlpath-in-rest-assured/

Part 8 – Getting and Verifying Response in Rest Assured – Only Fullstack
https://www.onlyfullstack.com/getting-and-verifying-response-in-rest-assured/

Part 9 – Different ways to provide body in Rest Assured – Only Fullstack
https://www.onlyfullstack.com/ways-to-pass-request-body-in-rest-assured/
 

How Authentication happens in Rest APIs?

What is OAuth2 Authentication used for Rest API?

OAuth 2 is an authorization framework that enables applications to obtain limited access to user accounts on an HTTP service, such as Facebook, GitHub, and DigitalOcean. It works by delegating user authentication to the service that hosts the user account, and authorizing third-party applications to access the user account. OAuth 2 provides authorization flows for web and desktop applications, and mobile devices.
Lets see different roles involved in the OAuth2 authorisation

The Third-Party Application: “Client”
The client is the application that is attempting to get access to the user’s account. It needs to get permission from the user before it can do so.

The API: “Resource Server”
The resource server is the API server used to access the user’s information.

The Authorization Server
This is the server that presents the interface where the user approves or denies the request. In smaller implementations, this may be the same server as the API server, but larger scale deployments will often build this as a separate component.

Authentication in Rest Assured

Here is a more detailed explanation of the steps in the diagram:

Step 1 – The client calls the http://localhost:8088/oauth/token and pass the user credentials
Step 2 – Authorization Server will authenticate the credentials and generate the access token and sends that access token to the client.
Steps 3 – Now we can the secure endpointhttp://localhost:8088/students and pass the access token into the Authorization header.
Step 4 – Resource Server will validate that access token and will send the response after validating the access token.

What are the advantages of this Authorization System?

Why can’t we send username and password in each rest call?

Username/Password
It is not a good idea to send credentials with each API requests. Even though you are sending credentials over ssl/tls(doesn’t provide end-end secure tunnel, known vulnerabilities !!), there are high chances of client being victim of MITM(Lan/Wifi level, ISP level, Country level) attacks.

Username(name, email)/Password(not too complex) are easily guessable. Definitely you would not want your users to enter 21+ characters password right ? for a better user experience !

Token Based
1 token(with expiry time untill user logout) is same as Username/Password
You should try implementing Oauth, JWT or Custom access/refresh token scheme. This approach itself will not provide more security if you are implementing it wrongly.
With tokens, you can provide users with more flexible session management transparency.

How to call the Rest API which Require Authentication in Postman?

We have seen how to start the rest api application to do the testing on your local system. If you don’t know then don’t worry, please follow the steps in below link –

LINK
In this rest apis we have one secured api names as /students which have the authentication mechanism implemented in Oauth2. So this api will need a valid access token otherwise it will return Uauthorized Access as response.
Below is the response when we don’t provide the access token while calling the /students api.
oauth2 without access token onlyfullstack
 
Lets call the /students api with access token.
Step 1. Call Oauth token api

Call the http://localhost:8088/oauth/token api or open the OAuth Token Request from out postman collection and pass below information.

1.1 Enter the http://localhost:8088/oauth/token and select http method as POST
1.2 Go to Authorization and select Basic Auth.
1.3 Enter Username and password as rest-assured / password

oath2 setup username password onlyfullstack

1.4 Go to Body section and select the type as x-www-form-urlencoded. Enter below keys and corresponding values.

oath2 setup header onlyfullstack

1.5 Hit send button to send the request to the Authorization Server

Step 2 – Authorization server authenticates and returns the token
Authorization server authenticates and returns the token. We will get the response as below. Copy the value of access token which we will need in calling out secured /students api.

oath2 access token onlyfullstack
 
Step 3 – Call /students api by passing the access token

3.1 Go to the OAuth Secured Get call request in out postman collection and navigate to the Authorization section.
3.2 Select the type as Bearer Token and paste the access token which we got in Step 2 in text box and hit Send. You will get the response as below.

oauth2 call with access token onlyfullstack

How to get the OAuth2 Authentication Bearer in Rest Assured?

OAuth2 Rest Assured example

Below code gets the access token from the OAuth2 service. Here we are passing the basic authentication details with basic method. We are also passing the key value pair of username and password of the resource in body with formParam method. 

@Test
public String getAccessTokenFromOAuth2() throws JSONException {

    Response response =
            RestAssured.given()
                    .baseUri("http://localhost:8088/")
                    .auth().preemptive().basic("rest-assured", "password")
                    .contentType("application/x-www-form-urlencoded")
                    .formParam("grant_type", "password")
                    .formParam("username", "onlyfullstack")
                    .formParam("password", "secret")
                    .when()
                    .post("/oauth/token");

    System.out.println("OAuth Response - " + response.getBody().asString());
    JSONObject jsonObject = new JSONObject(response.getBody().asString());
    String accessToken = jsonObject.get("access_token").toString();
    String tokenType = jsonObject.get("token_type").toString();
    System.out.println("Oauth Token with type " + tokenType + "   " + accessToken);
    return accessToken;
}

Authentication in rest assured

Lets call our /students rest end point. We got the access token from above method which we can pass with the help of oauth2 method.

package onlyfullstack;

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import onlyfullstack.models.Student;
import org.json.JSONException;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;

public class OAuth2Authorization {

    @Test
    public void callOAuth2ProtectedApi() throws JSONException {
        String accessToken = getAccessTokenFromOAuth2();
        Student request = new Student(1l, "Elon Musk", "elonmusk@gmail.com", "pccoe");

        Student response = RestAssured.given()
                .auth()
                .oauth2(accessToken)
                .baseUri("http://localhost:8088")
                .pathParam("student_rollNumber", "2")
                .body(request)
                .contentType(ContentType.JSON)
                .when()
                .get("/students/{student_rollNumber}")
                .then()
                .extract()
                .as(Student.class);
        System.out.println("Student api Response - " + response);
        Assert.assertEquals(response, request);
    }

    @Test
    public String getAccessTokenFromOAuth2() throws JSONException {

        Response response =
                RestAssured.given()
                        .baseUri("http://localhost:8088/")
                        .auth().preemptive().basic("rest-assured", "password")
                        .contentType("application/x-www-form-urlencoded")
                        .formParam("grant_type", "password")
                        .formParam("username", "onlyfullstack")
                        .formParam("password", "secret")
                        .when()
                        .post("/oauth/token");

        System.out.println("OAuth Response - " + response.getBody().asString());
        JSONObject jsonObject = new JSONObject(response.getBody().asString());
        String accessToken = jsonObject.get("access_token").toString();
        String tokenType = jsonObject.get("token_type").toString();
        System.out.println("Oauth Token with type " + tokenType + "   " + accessToken);
        return accessToken;
    }
}

Source Code
You can find the complete source code on below GitHub repository – 
https://github.com/onlyfullstack/rest-assured-tutorial

Rest Assured Tutorial
https://www.onlyfullstack.com/rest-assured-tutorial-for-beginners/