1

im new with rest assured and i make make one test to extract access token and some other params and i want to use these access token in the request headers for all other tests

is there away to set global header for all test methods i have, or make function to run once per all test and inject the required request header

 @Test
    public void getAccessToken (){
        Response body =
                given()
                        .params("username", "test@example.com","password","pass!","grant_type","password").post("https://example.test.com/Token")
                        .then()
                        .log().body()
                        .statusCode(200)
                        .extract().response();

        String access_token = body.path("access_token").toString();
        String token_type = body.path("token_type").toString();
        String refresh_token = body.path("refresh_token").toString();
        String Authorization = "bearer " + access_token;    }

}

Update i have added the following part below, but now getting 400 status code instead of 200 seems im missing something, down below i added to sample one of them works, and other one using RequestSpecification doesn't work

Worked as expected

public class PermissionTests  {

    Response body =
            given()
                    .params("username", "user@example.com","password","pass!","grant_type","password").post("https://test.example.com/Token")
                    .then()
                    .log().body()
                    .statusCode(200)
                    .extract().response();

    String access_token = body.path("access_token").toString();
    String token_type = body.path("token_type").toString();
    String refresh_token = body.path("refresh_token").toString();
    String Authorization = "bearer " + access_token;


@Test
public void addNewGraph(){

    given()
            .header("officeId",1)
            .header("organizationId",1)
            .header("refreshToken",refresh_token)
            .header("Authorization",Authorization)
            .when()
            .get("https://test.example.com/api/cases/recent")
            .then()
            .log().body()
            .statusCode(200);
    }
})

this sample doesnt work it returns 400 knowing that im using TestNG not JUnit

  public class PermissionTests  {

private static RequestSpecification requestSpec;

@BeforeClass
public static void AuthSetup() {

    Response body =
            given()
                    .params("username", "user@example.com","password","pass!","grant_type","password").post("https://test.example.com/Token")
                    .then()
                    .log().body()
                    .statusCode(200)
                    .extract().response();

    String access_token = body.path("access_token").toString();
    String token_type = body.path("token_type").toString();
    String refresh_token = body.path("refresh_token").toString();
    String Authorization = "bearer " + access_token;

    HashMap<String, String> defaultHeader = new HashMap<>();
    defaultHeader.put("officeId","1");
    defaultHeader.put("organizationId","1");
    defaultHeader.put("refresh_token",refresh_token);
    defaultHeader.put("Authorization", Authorization);

        RequestSpecBuilder builder = new RequestSpecBuilder();
        builder.addHeader("officeId", "1");
        builder.addHeader("organizationId", "1");
        builder.addHeader("refresh_token", refresh_token);
        builder.addHeader("Authorization", Authorization);

        requestSpec = builder.build();


 // specification = new RequestSpecBuilder()
////                .addHeaders(defaultHeader)
//                .addHeader("officeId","1")
//                .addHeader("organizationId","1")
//                .addHeader("refresh_token",refresh_token)
//                .addHeader("Authorization",Authorization)
//                .build();

}

@Test
public void addNewGraph(){

    given()
            .spec(requestSpec)
            .log().all()
            .when()
            .get("https://test.example.com/api/cases/recent")
            .then()
            .log().body()
            .statusCode(200);
    }
})

here is the log from last method

{
    "access_token": "eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjE2MSIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiJha2FtZWxAdHJhY2tlcnByb2R1Y3RzLmNvbSIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vYWNjZXNzY29udHJvbHNlcnZpY2UvMjAxMC8wNy9jbGFpbXMvaWRlbnRpdHlwcm92aWRlciI6IkFTUC5ORVQgSWRlbnRpdHkiLCJBc3BOZXQuSWRlbnRpdHkuU2VjdXJpdHlTdGFtcCI6ImJmODQ1MTEwLTk0ZDEtNGE0Yi05YzkxLThlNWQ1NDI2YTYxMyIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL2FkbWluIjoiVHJ1ZSIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL3NpZCI6IjE2MSIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL2VtYWlsYWRkcmVzcyI6ImFrYW1lbEB0cmFja2VycHJvZHVjdHMuY29tIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvb3JnYW5pemF0aW9uSWQiOiIxIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvb2ZmaWNlSWQiOiIxIiwicmVxdWlyZU1mYSI6IkZhbHNlIiwibmJmIjoxNTg4MTQ3MzMwLCJleHAiOjE1ODgxOTA1MzAsImlzcyI6Imh0dHBzOi8vdHJhY2tlcnByb2R1Y3RzLmNvbSIsImF1ZCI6ImM3MzJhY2U4MzRjZDQ4NTE5MGEzZTNhMjM2YTZhYzFkIn0.6pbDhYmyAXX9z46By4HxrCg_4HKRCSGq42FdhFoyA6s",
    "token_type": "bearer",
    "expires_in": 43199,
    "refresh_token": "d64dde50sd4be16ef209dcc5ss",
    "userName": "user@example.com",
    "userId": "sds",
    "deviceId": "eesdsde20d93e",
    "maxStringFieldLength": "10000",
    "opfs": "null",
    ".issued": "Wed, 29 Apr 2020 08:02:10 GMT",
    ".expires": "Wed, 29 Apr 2020 20:02:10 GMT"
}
Request method: GET
Request URI:    https://example.test.com/api/cases/recent
Proxy:          <none>
Request params: <none>
Query params:   <none>
Form params:    <none>
Path params:    <none>
Headers:        officeId=1
                organizationId=1
                refresh_token=d64dde50sd4be16ef209dcc5ss
                Authorization=bearer eyA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjE2MSIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzsdvY2xhaW1zL25hbWUiOiJha2FtZWxAdHJhY2tlcnByb2R1Y3RzLmNvbSIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vYWNjZXNzY29udHJvbHNlcnZpY2UvMjAxMC8wNy9jbGFpbXMvaWRlbnRpdHlwcm92aWRlciI6IkFTUC5ORVQgSWRlbnRpdHkiLCJBc3BOZXQuSWRlbnRpdHkuU2VjdXJpdHlTdGFtcCI6ImJmODQ1MTEwLTk0ZDEtNGE0Yi05YzkxLThlNWQ1NDI2YTYxMyIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL2FkbWluIjoiVHJ1ZSIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL3NpZCI6IjE2MSIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL2VtYWlsYWRkcmVzcyI6ImFrYW1lbEB0cmFja2VycHJvZHVjdHMuY29tIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvb3JnYW5pemF0aW9uSWQiOiIxIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvb2ZmaWNlSWQiOiIxIiwicmVxdWlyZU1mYSI6IkZhbHNlIiwibmJmIjoxNTg4MTQ3MzMwLCJleHAiOjE1ODgxOTA1MzAsImlzcyI6Imh0dHBzOi8vdHJhY2tlcnByb2RdZCI6ImM3MzJhY2U4MzRjZDQ4NTE5MGEzZTNhMjM2YTZhYzFkIn0.6pbDhYmyAXX9z46By4HxrCg_4HKRCSGq42FdhFoyA6s
                accept=application/json, text/plain, */*
Cookies:        <none>
Multiparts:     <none>
Body:           <none>

{
    "message": "GENERAL.ERROR",
    "errorId": "637237441331863542"
}

original request header from the browser

enter image description here

Amr Salem
  • 237
  • 1
  • 6
  • 19

2 Answers2

4

You can use the Specification Re Use of Rest Assured, Particularly the RequestSpecBuilder() since you need to re-use request data in different tests

public class PermissionTests {

private static RequestSpecification requestSpec;

@BeforeClass
public static void AuthSetup() {

    Response body = given().log().all()
            .params("username", "user@example.com", "password", "pass!", "grant_type", "password")
            .post("https://test.example.com/Token").then().log().body().statusCode(200).extract().response();

    String access_token = body.path("access_token").toString();
    String token_type = body.path("token_type").toString();
    String refresh_token = body.path("refresh_token").toString();
    String Authorization = "bearer " + access_token;

    RequestSpecBuilder builder = new RequestSpecBuilder();
    builder.addHeader("officeId", "1");
    builder.addHeader("organizationId", "1");
    builder.addHeader("refresh_token", refresh_token);
    builder.addHeader("Authorization", Authorization);

    requestSpec = builder.build();

}

@Test
public void addNewGraph() {

    given().spec(requestSpec).log().all().when().get("https://test.example.com/api/cases/recent").then().log()
            .body().statusCode(200);
}
}
Wilfred Clement
  • 2,674
  • 2
  • 14
  • 29
  • 1
    Thanks for you r answer it seems nice way, but when i use it i got unexpected response HashMap defaultHeader = new HashMap<>(); defaultHeader.put("officeId","1"); defaultHeader.put("organizationId","1"); defaultHeader.put("refresh_token",refresh_token); defaultHeader.put("Authorization", Authorization); specification = new RequestSpecBuilder() .addHeaders(defaultHeader) .setContentType(JSON) .build(); } given()..spec(specification).when().get("https://test.com") – Amr Salem Apr 28 '20 at 20:34
  • 1
    That's because you've been trying to send the headers as Map, I have updated the answer now and this should work – Wilfred Clement Apr 28 '20 at 20:49
  • 1
    still getting 400 private static RequestSpecification requestSpec; BeforeClass public static void AuthSetup() { Response body = given() .params("username",""....etc) String refresh_token = body.path("refresh_token").toString(); String Authorization = "bearer " + access_token; RequestSpecBuilder builder = new RequestSpecBuilder(); builder.addHeader("officeId", "1"); requestSpec = builder.build(); Test public void te(){ given() .spec(requestSpec) .log().all().when().get("https://test.com/api") } – Amr Salem Apr 29 '20 at 08:10
  • I cannot understand a word from the above, please edit the question with these detail and also paste the logs of the request, 400 is a BAD_REQUEST which means you are making a mistake in the request – Wilfred Clement Apr 29 '20 at 08:30
  • Formatted your code now, why can I not see the Authorization param being added to the request spec builder here ? `@BeforeClass public static void AuthSetup() { Response body = given().params("username","") String refresh_token = body.path("refresh_token").toString(); String Authorization = "bearer " + access_token; RequestSpecBuilder builder = new RequestSpecBuilder(); builder.addHeader("officeId", "1"); requestSpec = builder.build(); Test public void te(){ given().spec(requestSpec).log().all().when().get("test.com/api") }` – Wilfred Clement Apr 29 '20 at 08:33
  • i have updated my question, and also attached the console log for the beforeClass method and right below it the console log of the test itself – Amr Salem Apr 29 '20 at 08:56
  • I have updated the answer, the variable for the builder() was requestSpec but you've been marking it as "specification" in the request which is wrong, Try copying the complete details from the answer and try now – Wilfred Clement Apr 29 '20 at 09:01
  • Its not working i already did it same like your answer, sorry my updated part i was editing outside the editor maybe i didnt remove the old part as i did many retries, but i was already doing it same like in you answer it doesnt work unfortunately – Amr Salem Apr 29 '20 at 09:02
  • it wouldn't compile if i were adding it worng – Amr Salem Apr 29 '20 at 09:04
  • 2
    thank you man so much for the help, you code was correct, i just miss spelled something in header – Amr Salem Apr 29 '20 at 10:46
  • 1
    Happy to assist :) (Y) – Wilfred Clement Apr 29 '20 at 10:47
3

You could use RestAssured.requestSpecification to set a default request specification that will be sent with each request, e.g.

RestAssured.requestSpecification = new RequestSpecBuilder()
     .build().header("Authorization", "Bearer " + token);
splash
  • 13,037
  • 1
  • 44
  • 67
  • 1
    This solution gives an unexpected behaviour on other test classes with RestAssured when executing them sequentially. – spekdrum Aug 16 '22 at 14:22