Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rest Assured Bearer authentication

I am new to using Rest Assured,Java and Api testing so please be gentle with me. When I use rest assured to test an api that uses Bearer authentication the tests fail resulting in:- java.net.ConnectException: Connection refused: connect

I know the issue is likely to do with the authentication but am unsure on how to use "Bearer". I searched around and believe that somehow I need to make an initial request using my username and password. Then get a token back to be used for bearer authentication. Please can someone help me to do this with a very simple example?

My code is

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

}
like image 386
Klugsman Avatar asked Dec 07 '22 19:12

Klugsman


2 Answers

Response response =
      given()
          .headers(
              "Authorization",
              "Bearer " + bearerToken,
              "Content-Type",
              ContentType.JSON,
              "Accept",
              ContentType.JSON)
          .when()
          .get(url)
          .then()
          .contentType(ContentType.JSON)
          .extract()
          .response();
like image 154
PTT Avatar answered Jan 02 '23 00:01

PTT


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");
like image 25
Leandro Santana Avatar answered Jan 01 '23 22:01

Leandro Santana