如何在RestAssured中将基本身份验证作为请求标头的一部分传递?

时间:2018-12-16 09:19:09

标签: java api rest-assured

我是API测试和RestAssured的新手。我一直在尝试通过RestAssured访问API(受基本身份验证保护)http://restapi.demoqa.com/authentication/CheckForAuthentication,但不知道该怎么做。

这是我到目前为止编写的代码:

import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;

RestAssured.baseURI = "http://restapi.demoqa.com/authentication/CheckForAuthentication";
RequestSpecification request = RestAssured.given();

**I guess authentication code goes here but not sure**
Response response = request.get();

2 个答案:

答案 0 :(得分:1)

在RestAssured中,您可以这样操作:

("good" "bad")

还可以进行抢占式身份验证:

RequestSpecification request = RestAssured.given().auth().basic("username", "password");
Response response = request.get()

在官方Wiki页面上,有关于RestAssured身份验证的更多信息:https://github.com/rest-assured/rest-assured/wiki/Usage#authentication

答案 1 :(得分:0)

软件包jira_APIProject;

导入org.testng.annotations.Test;

import io.restassured.RestAssured; 导入io.restassured.authentication.PreemptiveBasicAuthScheme;

导入静态io.restassured.RestAssured。*;

import java.util.Base64;

公共类TestBasicAuth {

@Test
public void auth() {

    RestAssured.baseURI = "https://sdfsdfsdf-home.atlassian.net/";
    PreemptiveBasicAuthScheme authScheme = new PreemptiveBasicAuthScheme();
    authScheme.setUserName("sdfsdf.sdfsdf@gmail.com");
    authScheme.setPassword("sdfsdfsfdASDAFLq8U1XLsXZ02927");
    RestAssured.authentication = authScheme;

    given().header("Content-Type","application/json")
    .body("{\r\n" + 
            "    \"body\": \"Updated on 22nd april.\",\r\n" + 
            "    \"visibility\": {\r\n" + 
            "        \"type\": \"role\",\r\n" + 
            "        \"value\": \"Administrator\"\r\n" + 
            "    }\r\n" + 
            "}")

    .when().post("rest/api/2/issue/10004/comment")
    .then().log().all().assertThat().statusCode(201);

}

}