Generating and Using Access Tokens in a Rest API: A Complete Guide

HOME


public class AbstractHelper {
    
   String token;
   String accessToken;
   JsonPath jsonPath;

    public String generateToken() throws IOException {

        token = given().auth().preemptive()
                .basic(username, password)
                .contentType("application/x-www-form-urlencoded")
                .formParam("grant_type", "client_credentials")
                .when().post("https://example.com/accesstoken").asString();

        System.out.println("Token :" + token);

        jsonPath = new JsonPath(token);
        accessToken = jsonPath.getString("access_token");
        System.out.println("Access Token :" + accessToken);
        return accessToken;
    }

}

JsonPath jsonPath = new JsonPath(token);
accessToken = jsonPath.getString("access_token");
import java.io.IOException;

public class AccessToken_Example extends AbstractHelper {

    Response response;
    
   @Test
    public void testRequest() throws IOException {

        response = RestAssured.given()
                .auth().oauth2(generateToken()).when().get("https://localhost/8080/coreid").then()
                .extract()
                .response();

        System.out.println("Response :" + response.asString());
        int statusCode = response.getStatusCode();

        Assert.assertEquals(200,statusCode);
    }
}

Leave a comment