Search code examples
restpostmanbasic-authenticationrest-assuredweb-api-testing

Authorization in POST method using rest assured


I'm trying to send a POST method to my API and it returns 401 error instead of 200 OK.

Here is the thing:

Using Postman: POST request works fine.

Under Authorization section, I have selected Basic Auth and have provided Username/pwd.

Under Headers section, I have given X-application and Content-Type. My body in Postman is :

{
  "description": "TestAPIPostmannolast",
  "issue_type": {
    "id": "271341877549072389",
    "name": "Design"
  },
  "area": {
    "id": "271341877549072406"
  },
  "issue_id": "9d5ac7da-9626-11e8-9eb6-529269fb1459"
}

Using RestAssured: It fails with a 401 error.

package basic;

import io.restassured.response.Response;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import static io.restassured.RestAssured.given;

public class GetRequest {


    @BeforeClass
    public void setup() {

        RestAssured.baseURI = "https://123.com";

        RestAssured.basePath = "/field-management/api";

        RestAssured.authentication =    RestAssured.basic("username", "password");

    }

    @Test
    public void responseBody(){

        Response response = given()
                .header("X-application", "63fc4887-aed9-497f-bad5-d7ef2b90cdaf")
                .contentType("application/json")
                .body("{\n" +
                        "  \"description\": \"Intellij  \",\n" +
                        "  \"issue_type\": {\n" +
                        "    \"id\": \"271341877549072389\",\n" +
                        "    \"name\": \"Design\"\n" +
                        "  },\n" +
                        "  \"area\": {\n" +
                        "    \"id\": \"271341877549072406\"\n" +
                        "  },\n" +
                        "  \"issue_id\": \"2dd8ae7a-966e-11e8-9eb6-529269fb1459\n" +
                        "\n\"\n" +
                        "}")

                .when()
                .post("/projects/1879048400/areas/271341877549072406/issue/");

        System.out.println(response.body().asString());
    }

Response:

{"message":"Authentication Failed","errorKey":null}

Not sure why is it not working when I try it through RestAssured.


Solution

  • Adding the below code fixed it. Got this token from Postman

     .header("Authorization","Basic cG9sZWFyeTpBdXRoM250MWM=")