OAuth2 Login with Rest Assured Testcases

Munish Chandel | July 27, 2018 at 10:39 PM | 357 views

in OAuth2 protocol, a dedicated Authorization Server issues accessToken based on ClientId/ClientSecret and username/password combination. In addition, we have also to specify grant_type and scope for the request.

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()

        JSONObject jsonObject = new JSONObject(response.getBody().asString());
        accessToken = jsonObject.get("access_token").toString();
        logger.info("Oauth Token for " + email + " is " + accessToken);
1 clientId 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.

We can see that using OAuth2 credentials with RestAssured is quite an easy task.

Buy DRM Free PDF for Complete Collection of Interview Questions
Generic placeholder image
ebook PDF - Cracking Java Interviews v3.4 by Munish Chandel

240 real Java interview questions on core Java, concurrency, algorithms, design & data structures, spring, hibernate for Investment Bank, Healthcare IT, product and service based companies, Author : Munish Chandel, Price: 250, Type: PDF

Free Email Updates
Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Similar Articles:
  1. OAuth2 Login with Rest Assured Testcases
Facebook Page
Free Email Updates (100+ Subscribers)

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

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