How to pass authorization token in header in Rest assured?

HOME

 <dependencies>

       <!-- Rest Assured Dependency -->
      <dependency>
         <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>5.4.0</version>
        <scope>test</scope>
      </dependency>

        <!-- TestNG Dependency-->
      <dependency>
          <groupId>org.testng</groupId>
         <artifactId>testng</artifactId>
         <version>7.8.0</version>
         <scope>test</scope>
       </dependency>

</dependencies>

import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.testng.Assert;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;

public class BasicAuth_Demo {


    @Test
    public void createUser() {
        Response response = given()
                .auth()
                .preemptive()
                .header("Authorization", "Token")
                .header("Accept", "application/json")
                .contentType(ContentType.JSON)
                .body(validRequest)
                .when()
                .post("http://localhost:8080/users")
                .then()
                .extract()
                .response();

        int statusCode = response.getStatusCode();

        Assert.assertEquals(statusCode,200);
    }
}

package org.example;

import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.junit.Before;
import org.junit.Test;

import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

public class BasicAuth_Demo {

    private static final String BASE_URL = "https://httpbin.org/basic-auth/user/pass";
    private static final String TOKEN = "Basic dXNlcjpwYXNz";

    @Before
    public void setup() {
        given().baseUri(BASE_URL);
    }

    @Test
    public void validateToken() {


        Response response = given()
                .header("Accept", "application/json")
                .header("Authorization",TOKEN)
                .contentType(ContentType.JSON)
                .when()
                .get("https://httpbin.org/basic-auth/user/pass")
                .then()
                .log().all()
                .extract()
                .response();

        assertThat(response.getStatusCode(),equalTo(200));

    }

}

Leave a comment