放心承载认证

Klu*_*man 4 java authentication api rest-assured bearer-token

我是使用 Rest Assured、Java 和 Api 测试的新手,所以请对我保持温和。当我使用放心测试使用承载身份验证的 api 时,测试失败导致:- java.net.ConnectException:连接被拒绝:连接

我知道问题可能与身份验证有关,但不确定如何使用“承载”。我四处搜索并相信我需要以某种方式使用我的用户名和密码进行初始请求。然后取回令牌以用于承载身份验证。请有人用一个非常简单的例子帮助我做到这一点吗?

我的代码是

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

}
Run Code Online (Sandbox Code Playgroud)

PTT*_*PTT 11

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


小智 5

为了获取不记名令牌,您可以使用此代码来授权您的请求:

PreemptiveBasicAuthScheme authScheme = new PreemptiveBasicAuthScheme();
authScheme.setUserName("login");
authScheme.setPassword("password");
RestAssured.authentication = authScheme;
Run Code Online (Sandbox Code Playgroud)

获得令牌后,请通过以下方式将其发送到您的请求中:

response = given().auth().oauth2(token).get("http://mydomain/testpath/Id=2");
Run Code Online (Sandbox Code Playgroud)


Mik*_*y56 0

我的黄瓜步骤定义如下所示:

    // 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);  
}
Run Code Online (Sandbox Code Playgroud)

很大程度上取决于端点的编码方式。

当我想学习这种东西时,我会去放心的例子并搜索。

以这里为例。