This is very basic thing that in a corporate environment when you are dealing with Web Services then there would be some restriction over it like the same that you can not do login in your Gmail account without user name and password, which we call it Authentication.
There can be a multiple types of login credentials for example Basic Access and Paid Access. Here, with Basis Access means that you can do login into your account but you would be having very limited access over it. To get the full access of the web resources you have to buy a Premium access or paid access. So, this we call it Authorization.
How you will be dealing with such Rest Services where you should have valid login credentials to access its services?
Below code will help you to provide the solution.
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
public class Auth {
public static void main(String[] args) {
RestAssured.baseURI="Enter URI of any web service where Authentication is applied" ;
RequestSpecification req=RestAssured.given();
Response re=req.get();
String txt=re.body().asString();
System.out.println(txt);
System.out.println(re.getStatusLine());
}
}
Output of the above code if we don't have valid credentials to access the resources of the Web Service.
{
"StatusID": "FAULT_USER_INVALID_USER_PASSWORD",
"Status": "Invalid or expired Authentication key provided"
}
HTTP/1.1 401 Unauthorized
If you add only one more line in the above code with valid login credentials then your probelm will get resolved.
req.auth().preemptive().basic("Enter UserName", "Enter Password").when();
Now the final code would be
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
public class Auth {
public static void main(String[] args) {
RestAssured.baseURI="Enter URI of any web service where Authentication is applied" ;
RequestSpecification req=RestAssured.given();
req.auth().preemptive().basic("Enter UserName", "Enter Password").when();
Response re=req.get();
String txt=re.body().asString();
System.out.println(txt);
System.out.println(re.getStatusLine());
}
}
After execution of the above code see the output below:
{
"SuccessCode": "OPERATION_SUCCESS",
"Message": "Operation completed successfully",
"Username:Password": "User Name:Password",
"Authentication Type": "Basic"
}
HTTP/1.1 200 OK
To practice the above code look for the sample web services on google where authentication is required. I hope now you would be able to get the way that how you can access the web service where Authentication parameters need to be provided to access its resources.
If you come across with any doubt then please comment and I will try to revert at the earliest.
Best of Luck!
No comments:
Post a Comment