Rest Assured 的 Bearer 认证

9
我是一名新手,对Rest Assured、Java和Api测试并不熟悉,请大家耐心教导。当我使用rest assured来测试使用Bearer身份验证的api时,测试失败,结果出现以下错误:java.net.ConnectException:连接被拒绝。 我知道问题可能与身份验证有关,但不确定如何使用"Bearer"。我搜索了一下,认为我需要使用我的用户名和密码进行初始请求。然后得到一个令牌用于Bearer身份验证。 请问是否可以提供一个非常简单的示例来帮助我完成这个过程? 我的代码如下:
import com.jayway.restassured.RestAssured;
import static com.jayway.restassured.RestAssured.*;
import static org.hamcrest.Matchers.hasItem;

@BeforeTest
    public void setUp() {
        RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
        RestAssured.authentication =   preemptive().basic("username","password");

}

@Test
public void successfulTest() {
    given()
            .contentType("application/json; charset=UTF-8");

    when().

            get("http://mydomain/testpath/Id=2").
    then().
            statusCode(200);

}
5个回答

13
Response response =
      given()
          .headers(
              "Authorization",
              "Bearer " + bearerToken,
              "Content-Type",
              ContentType.JSON,
              "Accept",
              ContentType.JSON)
          .when()
          .get(url)
          .then()
          .contentType(ContentType.JSON)
          .extract()
          .response();

5
为了获得令牌,您可以使用以下代码对请求进行授权:
PreemptiveBasicAuthScheme authScheme = new PreemptiveBasicAuthScheme();
authScheme.setUserName("login");
authScheme.setPassword("password");
RestAssured.authentication = authScheme;

在获取到token之后,将其作为请求的一部分发送:

response = given().auth().oauth2(token).get("http://mydomain/testpath/Id=2");

0
Response postResponse = given().headers(cookieName, "Bearer " + cookieValue, "Content-Type",
                ContentType.JSON, "Accept", ContentType.JSON)
    .when().get(url).then().contentType(ContentType.JSON)
    .extract().response();

0
如果错误是“连接被拒绝”,那么更像是网络问题而不是身份验证问题。基本上,您还没有达到使用服务对客户端进行身份验证的阶段。 您可以检查一下服务是否在80端口之外的其他端口运行。如果是这种情况,只需在发送请求之前提供端口即可:
given().port(your_port_number)

在将请求放入代码之前,您可以使用更可视化的 REST 客户端应用程序来尝试您的请求,以确保它实际上是有效的。"Postman" 可能是一个不错的选择。


0

我的Cucumber步骤定义看起来像这样:

    // Class variables
    private String token_resource = "/yourApp/oauth/token?username=";
    private String endpoint_rest="https://your.app.domain.com/";
    private String acessToken;

    @When("^user gets access token using userId \"(.+)\" and password \"(.+)\"$")
public void getAccessToken(String userName, String password){
    RequestSpecification requestSpec = RestAssured.with();
    requestSpec.given().contentType("application/json");
    requestSpec.headers("Authorization", "Basic  your-string-here");
    Response response = requestSpec.post(endpoint_rest + token_resource + userName + "&password=" + password + "&client_id=yourApp&grant_type=password");
    String responseMsg = response.asString();
    System.out.println(">> responseMsg=" + responseMsg);
    assertTrue("Missing access token",responseMsg.contains("access_token"));
    System.out.println(">> Get Access token RESPONSE: " + responseMsg);

    DocumentContext doc = JsonPath.parse(responseMsg);
    acessToken= doc.read("access_token");

    System.out.println(" >> doc.read access_token= " + acessToken);  
}

很多事情取决于你的端点是如何编码的。
当我想学习这种东西时,我会去Rest-assured的示例并搜索。
例如这里

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接