Rest Assured Bearer authentication

末鹿安然 提交于 2019-12-04 18:31:33
Response response =
      given()
          .headers(
              "Authorization",
              "Bearer " + bearerToken,
              "Content-Type",
              ContentType.JSON,
              "Accept",
              ContentType.JSON)
          .when()
          .get(url)
          .then()
          .contentType(ContentType.JSON)
          .extract()
          .response();

In order to get the bearer token you can use this code to authorize your request:

PreemptiveBasicAuthScheme authScheme = new PreemptiveBasicAuthScheme();
authScheme.setUserName("login");
authScheme.setPassword("password");
RestAssured.authentication = authScheme;

After you get the token, send it in your request this way:

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

My Cucumber step definition looks like this:

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

Much depends on how your endpoint was coded.

When I want to learn this kind of thing I go to the Rest-assured examples and search.

Here for instance.

If the error was "Connection refused", it sounds more like a network issue instead of authentication. Basically you haven't reached the point to authenticate your client with the service. You can check to see if your service is running on a different port other than 80. If that's the case, just provide the port before sending out the request:

given().port(your_port_number)

You can use a more visualized rest client app to try your request to make sure it actually works before putting it into your code. "Postman" could be a good candidate.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!