0
votes

I want to get access token from the given REST-API call. I have tested this in postman and it is working fine which needs data to be entered in all 3 tabs( Authorization, Header and body and need to fire post method). Please find the attached screenshots for better clarity. Please guide me how to automate this with java and jayaway restassured library or any other solution.

Postman screenshot- Authorization tab

Postman Screenshot - Header tab

Postman screenshot- Body tab

Note: Username and password is different in Authorization and in different in Body tab

2

2 Answers

0
votes
RestAssured.baseURI = "http://URI";
Response res = given().header("Content-Type", "application/json")
                .body("{" + "   \"username\":\"[email protected]\"," + "   \"password\":\"ab@1234\""
                        + "}")
                .when().post("/api/token").then().log().all().assertThat().statusCode(200)
                .contentType(ContentType.JSON).extract().response();
String responseString = res.asString();
System.out.println(responseString);
JsonPath js = new JsonPath(responseString);
String str = js.get("data.access_token");
System.out.println(str);
0
votes

Assuming that your response will look like this:

{"token_type":"bearer","access_token":"AAAA%2FAAA%3DAAAAAAAA"}

You can try following Rest Assured example:

JsonPath jsonPath = RestAssured.given()
    .auth().preemptive().basic("username", "password")
    .contentType("application/x-www-form-urlencoded")
    .formParam("username", "johndoe")
    .formParam("password", "12345678")
    .formParam("grant_type", "password")
    .formParam("scope", "open_d")
    .when()
    .post("http://www.example.com/oauth2/token")
    .then()
    .statusCode(200)
    .contentType("application/json")
    .extract().jsonPath();

String tokenType = jsonPath.getString("token_type");
String accessToken = jsonPath.getString("access_token");