Search code examples
resttoken

How can I get authorization token in rest API using rest assured? Is it possible?


Currently using Postman I have to do post request to API_URL/login and I pass username and password and in return i get token see below:

Example Request:

/login
POST
Body
{
    "username": "admin",
    "password": "admin"
}
Return
{
    "token": "1234-56789-..."
}

Can you tell me how would I do .. i tried using .parameters but it says deprecated...


Solution

  • You'd have to know what the schema is of the response. For instance, if the output is like thus:

    {
        "success": true,
        "authorization_token": "eyJ0eXAiOiJCZWFy...",
        "refresh_token": "eyJ0eXAiOiJCZWFyZ...",
        "type": "Bearer",
    
        ...
    }
    

    Knowing the schema, you can extract the entire output and parse through it, like thus:

    import io.restassured.response.Response;
    
    Response response =  
            RestAssured.given().
                header("Content-Type", "application/json").
                body(loginPayload).
            when().
                post("/login").
            then().
                log().ifError().
                statusCode(200).
                contentType("application/vnd.api+json").
                body("$", hasKey("authorization_token")).                                   //authorization_token is present in the response
                body("any { it.key == 'authorization_token' }", is(notNullValue())).        //authorization_token value is not null - has a value
            extract().response();
    

    The auth token could then be set to a string variable

    String auth_token = response.path("authorization_token").toString();
    

    extract().response(); returns the entire reponse, but you could change this to extract().path("authorization_token") for just single string