放心,如何在 POST 请求后从响应 body 中提取生成的令牌并将其设置为 header

Rest assured, how to extract generated token from response body after POST request and set it to header

执行任何请求,我需要使用 POST 请求和 body {username:"somename", password:"somepass"} 执行身份验证, header Content-Type:application.json 这给了我生成令牌的响应,我需要将其粘贴为第二个 header,类似于 Authorization:generated-tokenkjhsdkjfvjbwjbQ== 以供进一步请求。 你能帮我一下吗?

我也有类似的需求,需要来回传递auth token,但是这个springrest template不放心。为此,我使用了客户端过滤器,它在响应时捕获令牌并根据请求将其设置为 header。放心搜索有没有类似的东西,可以的。 这是一个示例,https://github.com/rest-assured/rest-assured/wiki/Usage

自定义身份验证

Rest Assured 允许您创建自定义身份验证提供程序。您可以通过实现 io.restassured.spi.AuthFilter 接口(最好)并将其用作过滤器来执行此操作。例如,假设您的安全性包括将两个 header 加在一起形成一个名为 "AUTH" 的新 header(这当然是不安全的)。然后你可以这样做(Java 8 语法):

given().
        filter((requestSpec, responseSpec, ctx) -> {
            String header1 = requestSpec.getHeaders().getValue("header1");
            String header2 = requestSpec.getHeaders().getValue("header2");
            requestSpec.header("AUTH", header1 + header2);
            return ctx.next(requestSpec, responseSpec);
        }).
when().
        get("/customAuth").
then().
  statusCode(200);

您想使用 AuthFilter 而不是 Filter 的原因是在执行 given().auth().none() 时会自动删除 AuthFilters。 ...

我可能误解了这个问题,但根据我从中得到的信息,我认为这样的事情应该可行:

String token =
    given().
            header("Content-Type", "application/json").
            body(/* body content goes here */).
    when().
            post(/* route goes here */).
    then().
            extract().path("token").toString() 
            // the above path arg depends on the response you get from the call.

那么下一个电话会是这样的:

    given().
            header("Content-Type", "application/json").
            header("Authorization", token).
    when()...etc.

一些细节将取决于 API,但我一直使用这种格式。经常得到用户 ID 或令牌等的响应,并将其用于将来的调用。

更多关于在放心文档中提取的信息:https://github.com/rest-assured/rest-assured/wiki/Usage#extracting-values-from-the-response-after-validation

对我有用的变体:

String token = given()
                .contentType("application/json")
                .body(new User("someuser" , "123"))
                .when()
                .post(RestConfig.baseUrl+"/authentication-url")
                .then().extract().response().as(TokenResponse.class).getToken();

        given()
                .contentType("application/json")
                .header("Authorization", token)
                .get(RestConfig.baseUrl+"/some-path")
                .then()
                .statusCode(200)...

如果您想从响应中提取一个参数,那么这应该可行:

String jsonBody= ( enter request payload here )

ValidatableResponse response = RestAssured.given().baseUri(baseURL)
  .accept("application/json")
  .header("Content-Type","application/json")
  .body(jsonBody).when().post("/auth")
  .then().assertThat().statusCode(200)
  .log().all();
    
 String token=response.extract().path("token");