user3878725
user3878725

Reputation: 11

Rest Assured basic auth issue

I have an endpoint which works perfectly fine when I use Postman with Basic Auth. However, when I tried it in Rest Assured it returns 401. I have tried both different auth methods in rest assured and none of them worked for me so far. Need help!

    RequestSpecification requestSpec;
    String baseURI = "http://qa3-phoenix.labcorp.com";
    String basePath = "/phx-rest/healthcheck/ping";
    RestAssured.useRelaxedHTTPSValidation();
    RestAssured.baseURI = baseURI;
    requestSpec = new RequestSpecBuilder()
                .setContentType(ContentType.JSON)
                .build();

        Response response = RestAssured
                .given()
                    .spec(requestSpec)
                    .auth().basic("username","password")
                .when()
                    .get(basePath)
                .then()
                    .extract().response();

Upvotes: 1

Views: 4832

Answers (2)

Ondrej Burkert
Ondrej Burkert

Reputation: 7262

One can use directly the Authorization header with base64 encoded username and password and omit the auth() part.

Code example:

String authBasic = Base64.encode(String.format("%s:%s", username, password));
rest()
    .header("Authorization", String.format("Basic %s", authBasic))

Upvotes: 2

Kshetra Mohan Prusty
Kshetra Mohan Prusty

Reputation: 301

useRelaxedHTTPSValidation() is a workaround when the server is not using a valid certificate or you bump into SSLPeerUnverifiedException. In most of the scenarios this does not happen.

So try removing useRelaxedHTTPSValidation().

Can you also try the below approach:

While creating your RequestSpecification, can you add an object of authentication scheme to your RequestSpecification and then use that to create http requests.

    RequestSpecBuilder req = new RequestSpecBuilder();
    PreemptiveBasicAuthScheme auth = new PreemptiveBasicAuthScheme();
    auth.setUserName("");
    auth.setPassword("");
    req.setAuth(auth); 
    req.build();

May be you can think of creating your RequestSpec from a separate class or package for better re-use.

Let me know if this helps, or the stacktrace.

Upvotes: 0

Related Questions