RestAssured #11 - How to authenticate REST request

RestAssured #11 - How to authenticate REST request

• Cookie based authentication • Token based authentication

Introduction

To understand how to authenticate users in REST, we will use a private end-point which requires an authenticated user to access this end-point. For example, I am using this endpoint to create crocodiles created by a given user.

Endpoint - Get crocodiles

If you try to access this endpoint without authentication then you will get a 401 Unauthorized error as shown below

Cookie-based authentication

  • A cookie-based login is an authentication mechanism in which a server sends a cookie to the client after the client has successfully authenticated itself.

  • The client then sends the cookie back to the server with each subsequent request, allowing the server to identify the client and maintain the user's session.

How to authenticate using cookies in Postman

Request

Endpoint - https://test-api.k6.io/auth/cookie/login/

Body

{
    "username": "TestUser2023020720401211",
    "password": "1"
}

Response

Body

{
    "id": 674770,
    "username": "TestUser2023020720401211",
    "first_name": "TestUser",
    "last_name": "2023020720401212",
    "email": "TestUser2023020720401212@tester.com",
    "date_joined": "2023-02-12T12:39:06.903923Z"
}

Now when we try to access Get Crocodiles we should be able to get the details as we have done authentication

We can confirm that it has used cookie which was created before under Cookies tab under response section

TC1 - Validate 401 Auth Error When No Authentication used for My Crocodiles Endpoint

public class MyCrocodiles {
    private final String baseUri = "https://test-api.k6.io";
    private final String myCrocodilesPath = "/my/crocodiles/";

    private Response response;

    public MyCrocodiles(){
        RestAssured.baseURI = baseUri;
    }

    public void getMyCrocodilesWithoutAuth(){
        response = RestAssured.given().get(myCrocodilesPath);

        response.then().log().body();
    }

    public int getStatusCode(){
        return response.getStatusCode();
    }

    public String getResponseBodyUsingKey(String key){
        JsonPath jsonPath = response.jsonPath();
        return jsonPath.getString(key);
    }
}
public class ApiAuthenticationTest {

    private String userName = "TestUser2023020720401211";
    private String password = "1";

    private ApiAuthentication apiAuthentication;
    private MyCrocodiles myCrocodiles;

    @BeforeMethod
    public void setup(){
        apiAuthentication = new ApiAuthentication(userName,password);
        myCrocodiles = new MyCrocodiles();
    }

    @Test
    public void validateAuthErrorMyCrocodiles(){
        myCrocodiles.getMyCrocodilesWithoutAuth();
        Assert.assertEquals(myCrocodiles.getStatusCode(),401);
        Assert.assertEquals(myCrocodiles.getResponseBodyUsingKey("detail"),"Authentication credentials were not provided.");
    }
}

TC2 - Validate 200 Auth Success When Cookie Authentication used for My Crocodiles Endpoint

First, we need to get the Cookie value from the response -

public String getCookieValue(String cookieKey){
    return response.getCookie(cookieKey);
}

Then we can use the cookie method which is defined in RequestSpecification interface

RequestSpecification cookie(Cookie cookie)

public void getMyCrocodilesUsingCookieAuth(String cookieValue){
    response = RestAssured.given().cookie("sessionid",cookieValue).get(myCrocodilesPath);

    response.then().log().body();
}
public class ApiAuthentication {
    private final String baseUri = "https://test-api.k6.io";
    private final String cookieLoginPath = "/auth/cookie/login/";

    private String loginRequestBody;
    private Response response;

    public ApiAuthentication(String userName, String password){
        RestAssured.baseURI = baseUri;
        loginRequestBody = "{\"username\": \""+userName+"\",\"password\": \""+password+"\"}";
    }

    public void performLoginUsingCookieAuth(){
        response = RestAssured.given()
                .contentType(ContentType.JSON)
                .body(loginRequestBody)
                .log().body()
                .post(cookieLoginPath);

        response.then().log().body();
    }

    public String getCookieValue(String cookieKey){
        return response.getCookie(cookieKey);
    }

}
public class MyCrocodiles {
    private final String baseUri = "https://test-api.k6.io";
    private final String myCrocodilesPath = "/my/crocodiles/";

    private Response response;

    public MyCrocodiles(){
        RestAssured.baseURI = baseUri;
    }

    public void getMyCrocodilesWithoutAuth(){
        response = RestAssured.given().get(myCrocodilesPath);

        response.then().log().body();
    }

    public void getMyCrocodilesUsingCookieAuth(String cookieValue){
        response = RestAssured.given().cookie("sessionid",cookieValue).get(myCrocodilesPath);

        response.then().log().body();
    }

    public int getStatusCode(){
        return response.getStatusCode();
    }

    public String getResponseBodyUsingKey(String key){
        JsonPath jsonPath = response.jsonPath();
        return jsonPath.getString(key);
    }
}
public class ApiAuthenticationTest {

    private String userName = "TestUser2023020720401211";
    private String password = "1";

    private ApiAuthentication apiAuthentication;
    private MyCrocodiles myCrocodiles;

    @BeforeMethod
    public void setup(){
        apiAuthentication = new ApiAuthentication(userName,password);
        myCrocodiles = new MyCrocodiles();
    }

    @Test
    public void getCrocodilesUsingCookieAuth(){
        apiAuthentication.performLoginUsingCookieAuth();
        String cookie = apiAuthentication.getCookieValue("sessionid");
        myCrocodiles.getMyCrocodilesUsingCookieAuth(cookie);
        Assert.assertEquals(myCrocodiles.getStatusCode(),200);
    }
}

Token-based authentication

What is token-based authentication?

Token-based authentication is a method of securing a REST API by using tokens instead of session cookies.

When a user logs in to a REST API, a token is generated and sent back to the client. The client then includes the token with every subsequent request to the API. The API verifies the token and grants access to the requested resource if the token is valid.

Token-based authentication has several advantages over traditional session-based authentication. First, tokens are more secure than session cookies because they are not vulnerable to cross-site scripting (XSS) attacks. Second, token-based authentication allows for better scalability because it eliminates the need for the server to store session information.

How to authenticate using the token in Postman

Endpoint - https://test-api.k6.io/auth/token/login/

Using generated token to access API

Endpoint - https://test-api.k6.io/my/crocodiles/

How to authenticate using the token in RestAssured

TC 3 - Validate 200 Auth Success When Token Authentication used for My Crocodiles Endpoint

  • Send a request to the server to obtain the token. This is typically done through a login endpoint that accepts credentials and returns a token.
private final String authTokenEndpointPath = "/auth/token/login/";
loginRequestBody = "{\"username\": \""+userName+"\",\"password\": \""+password+"\"}";

public void performLoginUsingTokenAuth(){
    response = RestAssured.given()
            .contentType(ContentType.JSON)
            .body(loginRequestBody)
            .log().body()
            .post(authTokenEndpointPath);

    response.then().log().body();
}

• Retrieve the token from the response. The token is typically included in the response body or in a response header.

String token = response.getBody().jsonPath().getString("token");

• Use the token in subsequent requests by adding it as an authorization header.

public void getMyCrocodilesUsingTokenAuth(String tokenValue){
    response = RestAssured.given().header("Authorization","Bearer "+tokenValue).get(myCrocodilesPath);

    response.then().log().body();
}
public class ApiAuthentication {
    private final String baseUri = "https://test-api.k6.io";
    private final String authCookieEndpointPath = "/auth/cookie/login/";
    private final String authTokenEndpointPath = "/auth/token/login/";

    private String loginRequestBody;
    private Response response;

    public ApiAuthentication(String userName, String password){
        RestAssured.baseURI = baseUri;
        loginRequestBody = "{\"username\": \""+userName+"\",\"password\": \""+password+"\"}";
    }


    public void performLoginUsingTokenAuth(){
        response = RestAssured.given()
                .contentType(ContentType.JSON)
                .body(loginRequestBody)
                .log().body()
                .post(authTokenEndpointPath);

        response.then().log().body();
    }


    public String getResponseBodyUsingKey(String key){
        JsonPath jsonPath = response.jsonPath();
        return jsonPath.getString(key);
    }
}
public class MyCrocodiles {
    private final String baseUri = "https://test-api.k6.io";
    private final String myCrocodilesPath = "/my/crocodiles/";

    private Response response;

    public MyCrocodiles(){
        RestAssured.baseURI = baseUri;
    }

    public void getMyCrocodilesUsingTokenAuth(String tokenValue){
        response = RestAssured.given().header("Authorization","Bearer "+tokenValue).get(myCrocodilesPath);

        response.then().log().body();
    }

    public int getStatusCode(){
        return response.getStatusCode();
    }

    public String getResponseBodyUsingKey(String key){
        JsonPath jsonPath = response.jsonPath();
        return jsonPath.getString(key);
    }
}
public class ApiAuthenticationTest {

    private String userName = "TestUser2023020720401211";
    private String password = "1";

    private ApiAuthentication apiAuthentication;
    private MyCrocodiles myCrocodiles;

    @BeforeMethod
    public void setup(){
        apiAuthentication = new ApiAuthentication(userName,password);
        myCrocodiles = new MyCrocodiles();
    }

    @Test
    public void getCrocodilesUsingTokenAuth(){
        apiAuthentication.performLoginUsingTokenAuth();
        String token = apiAuthentication.getResponseBodyUsingKey("access");
        myCrocodiles.getMyCrocodilesUsingTokenAuth(token);
        Assert.assertEquals(myCrocodiles.getStatusCode(),200);
    }
}

Git Hub Repo Link - https://github.com/sksingh329/RestAssuredTutorials

Did you find this article valuable?

Support SUBODH SINGH by becoming a sponsor. Any amount is appreciated!