Rest Assured basic auth issue - rest-assured

I have an endpoint which works perfectly fine when I use Postman with Basic Auth. However, when I tried it in Rest Assured it returns 401. I have tried both different auth methods in rest assured and none of them worked for me so far. Need help!
RequestSpecification requestSpec;
String baseURI = "http://qa3-phoenix.labcorp.com";
String basePath = "/phx-rest/healthcheck/ping";
RestAssured.useRelaxedHTTPSValidation();
RestAssured.baseURI = baseURI;
requestSpec = new RequestSpecBuilder()
.setContentType(ContentType.JSON)
.build();
Response response = RestAssured
.given()
.spec(requestSpec)
.auth().basic("username","password")
.when()
.get(basePath)
.then()
.extract().response();

One can use directly the Authorization header with base64 encoded username and password and omit the auth() part.
Code example:
String authBasic = Base64.encode(String.format("%s:%s", username, password));
rest()
.header("Authorization", String.format("Basic %s", authBasic))

useRelaxedHTTPSValidation() is a workaround when the server is not using a valid certificate or you bump into SSLPeerUnverifiedException. In most of the scenarios this does not happen.
So try removing useRelaxedHTTPSValidation().
Can you also try the below approach:
While creating your RequestSpecification, can you add an object of authentication scheme to your RequestSpecification and then use that to create http requests.
RequestSpecBuilder req = new RequestSpecBuilder();
PreemptiveBasicAuthScheme auth = new PreemptiveBasicAuthScheme();
auth.setUserName("");
auth.setPassword("");
req.setAuth(auth);
req.build();
May be you can think of creating your RequestSpec from a separate class or package for better re-use.
Let me know if this helps, or the stacktrace.

Related

restsharp and Postman

I am attempting to get an OAuth2 access token from ZOHO using RestSharp code. The Postman simulation works correctly so I know there is something I'm missing in my code.
I always get an "invalid client id" result status. However in Postman, it works and returns a code when I click the "Get new access token". I have the same items as in the Postman authorization tab (client_id, client_secret, etc). In Postman, "Body" is set to "none", and there are no parameters or headers. The only difference between my code and postman, is that Postman requires the Callback URL. My code is trying to get the code using "self-client", which bypasses the callback URL.
I have tried several different alternatives to the request call including ParameterType.Body, and ParameterType.GetOrPost. Is GetOrPost the same as a form?
client = New RestClient(ZOHO_API_URL)
request = New RestRequest(TokenUrl, Method.POST)
request.AddHeader("content-type", "application/x-www-form-urlencoded") ' also tried: "application/json")
request.AddParameter("grant_type", "authorization_code",
ParameterType.GetOrPost)
request.AddParameter("client_id", Client_ID, ParameterType.GetOrPost)
request.AddParameter("client_secret", Client_Secret,
ParameterType.GetOrPost)
request.AddParameter("code", Grant_Token, ParameterType.GetOrPost)
response = client.Execute(request)
This is the translated Postman code for RestSharp:
var client = new RestClient("http://");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx");
request.AddHeader("cache-control", "no-cache");
IRestResponse response = client.Execute(request);
Any ideas on what I am doing wrong. I have tried to view the raw data coming across with Fiddler, but when I do that, Postman indicates a failure.
What code do I need to use to duplicate what Postman is doing?
How do I implement a callback URL if that is also required?
I quickly checked ZoHo REST API docs and it seems like you should use the Limited Input Device authentication flow.
From what I can understand from their help page, you indeed need to do a POST request, but parameters must be specified as query parameters:
https://accounts.zoho.com/oauth/v3/device/code?
client_id=1000.GMB0YULZHJK411248S8I5GZ4CHUEX0&
scope=AaaServer.profile.READ&
grant_type=device_request
You will also get better off with JSON set as a default for serialisation and content type just by using client.UseJson().
It maybe that Postman is following a redirect from your API endpoint as the functionality is different Postman verses RestSharp (possibly missing a trailing slash or similar).
Try adding
client.FollowRedirects = false;
to your RestSharp code and analyse the result.

Unable to get the LTPA token using Rest assured

I am new to rest assured, I want to perform some get and post for test data generation using rest assured. But I am unable to get the LTPA token and pass them to post. This works with postman but I want to do it through java. Any help
final String uri = "https://XXXX/Rest/XXXXX?user=XXXXX&pass=XXXX";
final Response response = RestAssured.given().relaxedHTTPSValidation().accept(ContentType.JSON).get(uri);
System.out.println(response.prettyPrint());
Map<String, String> allCookies = response.cookies();
System.out.println(allCookies);
Output
{JSESSIONID=XXXXXXX:-1}
but i do not see the LTPA2 token
Your LTPA2 token must be in Response headers.
You can get the response headers by
response.headers ();
In case if LTPA token is also not available in headers then share the screenshot of postman so I can help you out.

Sending OAuth token works in Postman but does not work in RestSharp

I tried to send a bearer token to an Auth0 API using Postman and it works perfectly.
I then tried the same using RestSharp (in c#) but it doesn't work at all.
Below is my code. I've tried many different formats but none of them work.. Is there any other way I can try to make it work?
var client = new RestClient("http://domain.auth0.com/api/v2/users");
RestRequest request = new RestRequest(Method.GET);
//request.AddHeader("authorization", "Bearer eyJhbGcJ9.eyJhdWQiOiJ6VU4hVWUE2.token");
//request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
//request.AddHeader("Accept", "application/json");
//RestClient client = new RestClient("http://domain.auth0.com");
//RestRequest request = new RestRequest("api/v2/users", Method.GET);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Accept", "application/json");
request.AddParameter("Authorization",
string.Format("Bearer " + "eyJhbGciOI1NiIsI9.eyJhdWQiOiWmVhTWpD2VycyI6eyJhY.token"),
ParameterType.HttpHeader);
//request.AddParameter("Authorization",
// String.Format("Bearer {0}", token),
//ParameterType.HttpHeader);
var response = client.Execute(request);
PS: the token was changed.
The problem is that you're using an HTTP URL. When you issue the first request the token is included, but you receive a redirect response informing that you should be calling the HTTPS endpoint.
Since RestSharp will not include the token in the second request performed automatically due to the first redirect response you get an unauthorized response.
You need to update the URL to be HTTPS which will prevent the redirect and as a consequence solve your problem. If you want to make multiple authenticated request using the same client you also change your code to be:
using RestSharp;
using RestSharp.Authenticators;
class Program
{
static void Main(string[] args)
{
// Use the HTTPS scheme
var client = new RestClient("https://[domain].auth0.com/api/v2/users");
client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(
"eyJhbGciJIUz.eyJhdWQi4QW5OXhCNTNlNDdjIn0.vnzGPiWA", // Update the token
"Bearer");
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
Console.WriteLine("{0}", response.StatusCode);
}
}
If you really need to handle redirects and still send the token, check: https://github.com/restsharp/RestSharp/issues/414

Decompressing REST response with GZIPInputStream

I'm trying to decompress a gzip:ed response i receive from a REST service:
Content-Encoding=[gzip], Content-Type=[application/json], Content-Length=[710] ...
I'm using the Grails REST Client Builder Plugin:
def response = new RestBuilder().get(HOST + "/api/..."){
contentType "application/json"
accept "application/json"
}
The returned response is a Spring ResponseEntity. I'm trying to decompress the data using GZIPInputStream:
String body = response.getBody()
new GZIPInputStream(new ByteArrayInputStream(body.getBytes())).text
This fails to Caused by ZipException: Not in GZIP format
Obviously there is something I'm doing wrong, but I can't figure out what. All advice is appriciated.
If you really need to keep using the Rest Client Builder you only need to modify your client code slightly:
def response = new RestBuilder().get(HOST + "/api/..."){
contentType "application/json"
accept byte[].class, "application/json" }
Note the extra parameter in the accept call - byte[].class - which signifies that RestTemplate should refrain from any parsing of the response.
To decompress you can now do:
new GZIPInputStream(new ByteArrayInputStream(response.body))
Yeah, I know, already answered with accept but some might still find it helpful in case switching Rest components is not an option.
I never managed to get it to work with grails / groovy libraries, so i switched to spring and httpcomponents:
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create().build());
RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
ResponseEntity<String> response = restTemplate.exchange(
"some/url/", HttpMethod.GET, new HttpEntity<Object>(requestHeaders),
String.class);
Which decoded gzip automatically and thus there are no longer any need for manual decoding.

Tridion UGC service and oAuth authentication

I've a problem when trying to do a webrequest to UGC and authenticate using oAuth. I'm making a webrequest such as:-
WebRequest wr = WebRequest.Create("http://ugc.service/odata.svc/Ratings(Id=200)");
wr.Headers["authorization"] = "OAuth " + auth;
Where auth is my token returned from the access_token.svc. According to the documentation the token returned from the service should be something like:-
HufXeuUt%2FYYElA8SYjJOkUkrXxV9dyXRirmKhjW%2Fb%2FU%3D
However, what I'm being returned from access_token.svc is more like:-
{"access_token":"client_id%3dtestuser%26expiresOn%3d1361898714646%26digest%3d%2fW%2fvyhQneZHrm1aGhwOlgLtA9xGWd77hkxWbjmindtM%3d","expires_in":300}
I've parsed the JSON to extract various strings and attempted to pass these through to the authorization but whatever I try I get an error in the logs - "ERROR OAuth2AccessToken - Digest is wrong." Exactly what part of the token and in what format should I be passing through to authorization?
Many thanks
John
Like you mentioned, the protocol is this:
You make a post request to the access token end-point to get a token (you need to provide here your client_id and your client_secret as headers or as query parameters);
You get an answer similar to this: {"access_token":"sometoken","expires_in":300};
2.1 Worth knowing is that the token is url encoded and in UTF-8 format so, on Java side you need to do URLDecoder.decode("sometoken", "UTF-8"); while on .NET side you need to do HttpUtility.UrlDecode("sometoken", System.Text.Encoding.UTF8);;
Your next request needs to include the authorization header. On Java side you do builder.header("authorization", "OAuth " + decodedTokenString); while on .NET side you can use Client.Headers["authorization"] = "OAuth " + DecodedTokenString;
Worth mentioning is that the SharedSecret defined in the cd_webservice_conf.xml (/Configuration/AuthenticationServer/SharedSecret/) of the TokenAccessPoint needs to be the same as the SharedSecret defined in the cd_ambient_conf.xml (/Configuration/Security/SharedSecret/) of the (WebService)EndPoint.
Are you sure you decoded properly the token gotten from the server? Are you sure that you configured the proper SharedSecret in the two configuration files?
Hope this helps.

Resources