11

I want to test a Rest API which require authentication, before getting the Json response. FOr exa. If i want to visit rest API: http://192.168.xx.xx:9000/dashboards/all/list/m1/p1/sch1

then

if I am not already logged in , then this will redirect me to Login HTML page, and after login, this will show me the Json output.

Now I want to write a Rest assured code in java for same: I dont know , whether this is possible to do login using this or not.

SO I written a simple code for same::

public class TestNGSimpleTest1 {

    @Test
    public void testAdd() {
            //expect().
            //statusCode(400).
            //body("Status", equalTo("Success")).
            //when().
            //get("http://localhost:9000/dashboards/all/list/m1/p1/sch1");
            //System.out.println("Response received is ::" +res);   
            Response res = get("http://localhost:9000/dashboards/all/list/m1/p1/sch1");
            assertEquals(200,res.getStatusCode());
            String json = res.asString();
            System.out.println("Response received is :: " +json);
    }

So here instead of getting the Json response, I am getting the HTML source page response.

So, my question is if possible, how to do login and get the Json response.

Thanks in advance.

undefined
  • 3,464
  • 11
  • 48
  • 90
  • 1
    for rest-assured see [this link here](http://code.google.com/p/rest-assured/wiki/Usage#Authentication) which shows how to do basic or OAut authentification or [this link here](http://code.google.com/p/rest-assured/issues/detail?id=87) if you need preemptive authentication. – Roman Vottner Jan 05 '14 at 09:32
  • Actually, I tried this link also, but the problem is Login page where it redirect is , an html page.. using ur link, this is just showing the HTML page still. – undefined Jan 05 '14 at 17:35
  • What type of authentication are you using? Just a login-page which contains a backing database call which checks the entered username and password - so no basic auth or OAuth? This seems rather strange though especially for a REST based web service which is primarily intended for being accessed by applications rather than humans (so no input in form-fields and clicking a submit button). What server framework do you use? CXF, Restlet, ...? Have you already tried to connect to your REST service using SoapUI? – Roman Vottner Jan 05 '14 at 17:50
  • I will update about it soon because I am not sure of the answer you are asking for. Wheneever I make a http request like : http://192.168.xx.xx:9000/dashboards/all/list/m1/p1/sch1 , then it redirects to a HTML login page where this ask for username and password. I will get more details by tomorrow and will update you. Thanks. – undefined Jan 05 '14 at 18:05
  • @RomanVottner Discussed with our Dev team .. they designed the Rest API in such a way that for any Rest API request this will redirect to a HTML login page. They agreed to change this authentication behaviour in QA test environment but Is this the correct approach?? – undefined Jan 06 '14 at 17:35

7 Answers7

10

If you are using default authentication from JIRA, then preemptive authentication is what you need. Below are the sample code.

RestAssured.baseURI = System.getProperty("baseurl");
PreemptiveBasicAuthScheme authScheme = new PreemptiveBasicAuthScheme();
authScheme.setUserName("admin");
authScheme.setPassword("admin");
RestAssured.authentication = authScheme;

The sample code will help you do the authentication before every request you send.

Powpow
  • 150
  • 1
  • 8
7

This method works great. In addition to submitting the login credentials, it also verifies the 200 status code at the same time

given().auth().basic(username, password).when().get("/uri/").then().statusCode(200);
2

You can try this:

given().auth().preemptive().basic(username, password).when().get("{yourApiURL}").then().statusCode(200);
Abhishek Gurjar
  • 7,426
  • 10
  • 37
  • 45
Rafa
  • 21
  • 1
2
package jira_APIProject;

import org.testng.annotations.Test;

import io.restassured.RestAssured;
import io.restassured.authentication.PreemptiveBasicAuthScheme;

import static io.restassured.RestAssured.*;

import java.util.Base64;

public class TestBasicAuth {

    @Test
    public void auth() {
        
        RestAssured.baseURI = "https://jjjjjjj-home.atlassian.net/";
        PreemptiveBasicAuthScheme authScheme = new PreemptiveBasicAuthScheme();
        authScheme.setUserName("kkkkkkkkkk.kkkkkkkkkk@gmail.com");
        authScheme.setPassword("lllllllll8U1XLsXZ02927");
        RestAssured.authentication = authScheme;

        given().header("Content-Type","application/json")
        .body("{\r\n" + 
                "    \"body\": \"Updated on 22nd april.\",\r\n" + 
                "    \"visibility\": {\r\n" + 
                "        \"type\": \"role\",\r\n" + 
                "        \"value\": \"Administrator\"\r\n" + 
                "    }\r\n" + 
                "}")
        
        .when().post("rest/api/2/issue/10004/comment")
        .then().log().all().assertThat().statusCode(201);
        
    }
}
npe
  • 19
  • 8
Hemant P
  • 21
  • 2
1

You probably looking for form authentication:

given().auth().form("username", "password"). .. 

Optionally you need to provide an instance of FormAuthConfig as a third parameter to describe how your HTML login page looks like.

Johan
  • 37,479
  • 32
  • 149
  • 237
0

Below code worked for me :

JsonPath response = RestAssured
.given()
    .header("Authorization", "Basic " + encodedString)
    .when()
    .get(GET_PUSH_API)
.then()
    .statusCode(401)
    .extract().jsonPath();

Reference - Example 14 : https://www.programcreek.com/java-api-examples/index.php?api=com.jayway.restassured.RestAssured

Spartan
  • 3,213
  • 6
  • 26
  • 31
0
public void LoginRequest() {
    RestAssured.baseURI = BASE_URL;
    RequestSpecification request  = RestAssured.given().auth().preemptive().basic(USERNAME, PASSWORD);
    response = request.get("​/Account​/v1​/User");
Forough Omidvar
  • 111
  • 1
  • 5
  • 2
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Sabito stands with Ukraine Oct 10 '20 at 12:07