RestAssured and Bearer token

Viewed 1351

Very new to RestAssured and authentication in general.

I have an API I can make a get request to in Postman with client credentials. It returns a bearer token.

I am now trying to get this to work with cucumber and restassured.

So very we have this code where it tries to get the bearer token for the next step which is the API call.

@Given("^the user has a valid authentication token for credentials$")
public void the_user_with_credentials_something_and_something_has_a_valid_authentication_token() throws Throwable {
    
        RestAssured.baseURI=SCN_CONTEXT.getProp().getExternalUri();
        Response accessTokenResponse = given()
                 .header("Content-Type", "application/json")
                 .queryParams("client_id", SCN_CONTEXT.getProp().getClientId())
                 .queryParams("client_secret", SCN_CONTEXT.getProp().getClientSecret())
                 .when().log().all().get(APIResources.valueOf("oAuthAPI").getValue());
         
         System.out.println(accessTokenResponse.getStatusCode());
         SCN_CONTEXT.get_SCN().write("accessTokenResponse: " + accessTokenResponse.getStatusCode());

          JsonPath js=new io.restassured.path.json.JsonPath(accessTokenResponse.body().asString());
            id_token="Bearer " + js.getString("id_token");
            SCN_CONTEXT.setId_token(id_token);
            SCN_CONTEXT._SCN.write("Authentication Token is: " + id_token);
            
    }

The externalUri used is the token access uri I have used in Postman.

But on doing this I get a 403 and the token is null

Console log: (anything with ? I removed)

Request method: GET
Request URI:    https://?.com/?/v1/?/oauth/token?client_id=?&client_secret=?
Proxy:          <none>
Request params: <none>
Query params:   client_id=?
                client_secret=?
Form params:    <none>
Path params:    <none>
Headers:        Accept=*/*
                Content-Type=application/json; charset=UTF-8
Cookies:        <none>
Multiparts:     <none>
Body:           <none>
403
1 Answers

A lot of things to look at over here, For a similar requirement I had the following in the POSTMAN console. Seemingly this might be a GET call but technically this is a POST call

The authorization is Base64 encoded which is sent as a header and the query parameters are grant_type and scope

The Rest Assured code for this will be

given().header("Content-Type", "application/x-www-form-urlencoded").auth().preemptive()
        .basic("abc", "def")
        .queryParam("grant_type", "client_credentials").queryParam("scope", "123").when()
        .post("ghi").then().extract().response();

enter image description here

Related