OAuth2 Login with Rest Assured Testcases

Carvia Tech | May 05, 2019 | 1 min read | 679 views

An OAuth2 Authorization Server is responsible for issuing JWT accessToken/refreshToken when a resource owner presents its credentials. credentials typically consists of ClientId/ClientSecret, username/password, grant_type and scope of the request.

In this tutorial we will use RestAssured library to hit the token endpoint on authorization server and generate the accessToken.

Issue AccessToken based on resource owner credentials
private void login(String email, String pwd) throws JSONException {
    logger.info("Getting OAuth Token from server - {}", baseURI);
    Response response =
            given().auth().preemptive().basic("<cliendId>", "<clientSecret>") .   (1)
                    .formParam("grant_type", "password")
                    .formParam("username", email)
                    .formParam("password", pwd)
                    .formParam("scope", "read").when()
                    .post(baseURI + "/oauth/token");

    JSONObject jsonObject = new JSONObject(response.getBody().asString());
    accessToken = jsonObject.get("access_token").toString();
    logger.info("Oauth Token for " + email + " is " + accessToken);
1 cliendId and clientSecret are basic credentials provided by OAuth2 Provider

Now this accessToken can be used to make calls to the protected resource server using the below syntax:

Making Call to actual service using recently acquired AccessToken
public void uploadData() throws IOException {
        String jsonString = IOUtils.toString(DataLoader.class.getClassLoader().getResourceAsStream("daily_feed.json"), Charset.forName("UTF-8"));

        Response response = given().auth().oauth2(accessToken)  (1)
        String responseBody = response.getBody().asString();
        if (response.getStatusCode() >= 200 && response.getStatusCode() <= 299) {
            logger.info("Create Daily Feed Response = " + responseBody);
        } else {
            logger.error("Error creating daily feed = {}", responseBody);
1 Passing the OAuth2 AccessToken in request.

That’s all!

If you are looking to use RestTemplate instead, then follow this article- Self signed HttpClient and RestTemplate for testing

Top articles in this category:
  1. Top 50 SDET Java Programming Interview Questions & Answers
  2. OAuth2 protected resources using RestTemplate
  3. Commonly used Http methods in RESTful services
  4. Using h2load for REST API benchmarking
  5. Self signed HttpClient and RestTemplate for testing
  6. SDET Java Role - Essential Skills
  7. How to reverse a number in Java

Find more on this topic:
SDET Interviews image
SDET Interviews

End to end automation testing using Selenium Web Driver, Rest Assured, JMeter, Junit, TestNG etc.

Last updated 1 month ago

Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info