简体   繁体   中英

How to set cookie with the request using rest assured?

I need to automate the rest API. The API is secured with Spring security.

Below is the code to authenticate :

Response response = given().auth()
                    .form(userName, password,   FormAuthConfig.springSecurity().withLoggingEnabled(new LogConfig(captor, true)))
                    .post("/home/xyz.html");

            Assert.assertTrue("Error occurs", response.statusCode() == 302);

            if (response.statusCode() == 302) {
                Cookie cookie = response.getDetailedCookie("JSESSIONID");
                result.actualFieldValue = "User Authenticated: Session ID ->" + cookie.getValue();
                System.out.println("Cookie set : "+cookie.getValue());
                apiTestSessionID = cookie.getValue();
            }

The user logs in and return 302 status, means redirection.I found the cookie and set in some global variable.

Now, i set the cookie with the request :

RequestSpecification reqSpecification = new RequestSpecBuilder().addCookie("JSESSIONID", AbstractBaseClass.apiTestSessionID).build();

            Map<String, String> parameters = new HashMap<String, String>();
            parameters.put("cstmrID", "000N0961");
            parameters.put("pageNumber", "1");
            parameters.put("pageSize", "10");
            parameters.put("sortColumnName", "FIELD_NM");
            parameters.put("sortDir", "asc");
            parameters.put("filterColumnName1", "");
            parameters.put("filterColumnName2", "USER_UPDT_EMAIL_ID");
            parameters.put("filterValue2", "");

            reqSpecification.queryParams(parameters);

            Response response = given().spec(reqSpecification).when().get("/service/customerConfig").thenReturn();
            System.out.println(response.asString());

But in response i get the login page HTML . I am not able to understand where i am doing wrong.

Assumptions :

  1. Since with the post request, 302 is returned, do i need to redirect to the next url and after that perform get request with the cookie.
  2. Is this the right way to set the cookie with the request.
  3. Do i need to set the headers with the request. If yes, then following is the header info. Do i need to set all of them?

GET /example.com/abc.html HTTP/1.1 Host: example.com Connection: keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp, / ;q=0.8 Accept-Encoding: gzip, deflate, sdch Accept-Language: en-US,en;q=0.8 Cookie: JSESSIONID=C70A69F1C60D93DC3F8AC564BDE3F4DE.lon2mcaqaapp002; __utma=185291189.2055499590.1460104969.1460104969.1460618428.2

I'm new to Rest Assured too, but I've just written the similar test.

I suggest that you write a private authenticate() method:

private static String authenticate() {
    given()
        .auth()
        .form(userName, password,FormAuthConfig.springSecurity().withLoggingEnabled(new LogConfig(captor, true)))
    when()
        .post("/home/xyz.html").
    thenReturn()
        .getDetailedCookie("JSESSIONID");
}

and then use the cookie in the request:

given()
    .cookie(authenticate())
when()
    .get("/service/customerConfig").
thenReturn();

But I'm not sure how do you check the statusCode here.

It's also a good idea to use .log().all() to see the logs.

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.http.Cookies;

private Cookie cookie;

@BeforeClass
public void exampleOfLogin() {
    String body = String.format("//json");
    cookies = RestAssured.given()
            .contentType(ContentType.JSON)
            .when()
            .body(body)
            .post("www.test_test.com")
            .then()
            .statusCode(200)
            .extract()
            .response()
            .getDetailedCookies();
}

@Test
public void performActionsBasedOnCookies() {
//set cookies before making a post request and check the returned status code
    RestAssured.given()
            .cookies(cookies)
            .contentType(ContentType.JSON)
            .when()
            .post("www.test_url.com")
            .then()
            .statusCode(200);
}

I had tried using getDetailedCookies() for retrieving authentication/authorization cookies and set that as given().cookies(cookies).when().post(url).

But I was not able to retrieve all cookies needed for authorization.

Here is how I did it.

  1. I created an instance variable of

    import io.restassured.filter.cookie.CookieFilter

    CookieFilter filter = new CookieFilter();

  2. Used cookieFilter in authentication/authorization call

    RestAssured.given().filter(filter).body(body).post(url).andReturn();

  3. Use the same filter in the request that needs authentication/authorization cookie.

    RestAssured.given().filter(filter).body(body).post(url);

The filter is filled with all the cookies from the authentication call.

Here is a basic code to illustrate the idea. You can expand this to your step definitions

import io.restassured.RestAssured;
import io.restassured.filter.cookie.CookieFilter;
import io.restassured.response.Response;
import org.junit.Test;

public class RestAssuredRunner {

    CookieFilter filter = new CookieFilter();




@Test
    public  void testAuthenticatedRequest(String[] args) {


        String url = "http://mywebsitelogin.com";
        String body = "userId=1212&&password=232323";
        //Authentication request
        Response response = RestAssured.given().filter(filter).body(body).post(url).andReturn();
        //Request that needs authentication
        RestAssured.given().filter(filter).body(body).post(url);
    }


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM