简体   繁体   English

如何使用放心请求设置cookie?

[英]How to set cookie with the request using rest assured?

I need to automate the rest API. 我需要自动化其余的API。 The API is secured with Spring security. API通过Spring安全保护。

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. 用户登录并返回302状态,表示重定向。我找到了cookie并设置了一些全局变量。

Now, i set the cookie with the request : 现在,我使用请求设置cookie:

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 . 但作为回应我得到登录页面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. 由于使用post请求,返回302,我是否需要重定向到下一个url,然后执行获取cookie的请求。
  2. Is this the right way to set the cookie with the request. 这是使用请求设置cookie的正确方法。
  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; GET /example.com/abc.html HTTP / 1.1主机:example.com连接:keep-alive Cache-Control:max-age = 0升级 - 不安全请求:1用户代理:Mozilla / 5.0(Windows NT 6.1; WOW64)AppleWebKit / 537.36(KHTML,与Gecko一样)Chrome / 55.0.2883.87 Safari / 537.36接受:text / html,application / xhtml + xml,application / xml; q = 0.9,image / webp, / ; q = 0.8接受 -编码:gzip,deflate,sdch Accept-Language:en-US,en; q = 0.8 Cookie:JSESSIONID = C70A69F1C60D93DC3F8AC564BDE3F4DE.lon2mcaqaapp002; __utma=185291189.2055499590.1460104969.1460104969.1460618428.2 __utma = 185291189.2055499590.1460104969.1460104969.1460618428.2

I'm new to Rest Assured too, but I've just written the similar test. 我也是Rest Assured的新手,但我刚刚写了类似的测试。

I suggest that you write a private authenticate() method: 我建议你写一个私有的authenticate()方法:

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: 然后在请求中使用cookie:

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

But I'm not sure how do you check the statusCode here. 但我不知道你怎么在这里查看statusCode

It's also a good idea to use .log().all() to see the logs. 使用.log().all()来查看日志也是个好主意。

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). 我曾尝试使用getDetailedCookies()来检索身份验证/授权cookie,并将其设置为given()。cookies(cookies).when()。post(url)。

But I was not able to retrieve all cookies needed for authorization. 但我无法检索授权所需的所有cookie。

Here is how I did it. 我就是这样做的。

  1. I created an instance variable of 我创建了一个实例变量

    import io.restassured.filter.cookie.CookieFilter import io.restassured.filter.cookie.CookieFilter

    CookieFilter filter = new CookieFilter(); CookieFilter filter = new CookieFilter();

  2. Used cookieFilter in authentication/authorization call 在身份验证/授权调用中使用cookieFilter

    RestAssured.given().filter(filter).body(body).post(url).andReturn(); 。RestAssured.given()过滤器(过滤器)。体(主体).POST(URL).andReturn();

  3. Use the same filter in the request that needs authentication/authorization cookie. 在需要身份验证/授权cookie的请求中使用相同的过滤器。

    RestAssured.given().filter(filter).body(body).post(url); 。RestAssured.given()过滤器(过滤器)。体(主体).POST(URL);

The filter is filled with all the cookies from the authentication call. 过滤器中填充了身份验证调用中的所有Cookie。

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);
    }


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在REST服务的请求标头中设置cookie - How to set cookie in request header for REST service 如何使用一个 API 的 cookie 到另一个 API 并使用 REST 保证库在 Java 中运行 API 调用链 - How to use the cookie of one API to another and run the chain of API calls in Java using the REST assured library 在 rest assured java 中使用基于 cookie 的身份验证处理并发登录 - Handling concurrent login using cookie based authentication in rest assured java 如何使用Rest Client在ruby中获取请求的cookie详细信息 - How to get cookie details of the request in ruby using rest client 使用请求模块,如何处理请求响应中的“set-cookie”? - Using requests module, how to handle 'set-cookie' in request response? 如何使用Fiddler在请求中设置cookie? - How can I set a cookie in a request using Fiddler? 如何通过$ .post请求使用php设置cookie - How to set cookie using php through $.post request Mule将JSESSIONID从第一个REST请求设置为第二个REST请求或如何将cookie放入其中 - Mule Set JSESSIONID from first into 2nd REST request or how to put the cookie through 保证放心的cookie或授权标头保持最新 - Rest-Assured keep cookie OR Authorization header up to date 如何在Javascript中为websocket设置请求标头中的cookie? - How to set cookie in request header for websocket in Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM