Login issue with Restassured api testing - api

I tried to generate the token from login request.It is successful in postman tool and success in soapui groovy script.But I couldnot do via rest assured library.Below are the screenshot where the request uses Body - form-data with username and password.
I have tried the using queryparams, formparam but getting the below error.Kindly help me to solve the error.
<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.4.4</center>
</body>
</html>
Rest assured code:
Map<String, String> formParams = new HashMap<>();
formParams.put("username", "test");
formParams.put("password", "welcome");
Response response = RestAssured.given().config(RestAssured.config().redirect(redirectConfig().followRedirects(false)).encoderConfig(EncoderConfig.encoderConfig().encodeContentTypeAs("multipart/form-data", ContentType.TEXT)))
.queryParams(formParams)
.post("http://posturl");

You are sending the parameters as a query, not as form params.
Also, looks like you need to follow the redirect, since you're getting a 301, so you need followRedirects(true) instead of false.
You need to do it this way:
Response response = RestAssured.given()
.config(RestAssured.config()
.redirect(new RedirectConfig().followRedirects(true))
.encoderConfig(EncoderConfig
.encoderConfig()
.encodeContentTypeAs("multipart/form-data", ContentType.TEXT)))
.formParams(formParams)
.post("http://posturl");

Related

hitting an endpoint from angular8 returns 404

This is my first exercise in angular8. I am on the attempt to make a form that consumes an API written in springboot. The api written in spring-boot is never executed when trying to consume it from angular8 and here is the endpoint
http://localhost:8080/api/startreg
#PostMapping("/startreg")
public ResponseData<Activity> addReg(
#RequestParam(value="firstDate") String firstDate,#RequestParam(value="secondDate") String secondDate
,#RequestParam(value="username") String username) {
try {
Here is the service.ts script
private baseUrl = 'http://localhost:8080/api/startreg';
createReg(activity: Object): Observable<Object> {
return this.http.post('${this.baseUrl}', activity);
}
the html file of the angular8 is shown
<form (ngSubmit)="onSubmit()">
<div class="col-md-3 col-sm-5 col-xs-12 gutter">
<div class="sales">
<h2>From:</h2>
<div class="btn-group">
<select [(ngModel)]="activity.firstDate" class="form-control" name="firstDate">
when I attempt to submit the form, from the browser console below error
HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:4202/$%7Bthis.baseUrl%7D", ok: false, …}
Please where I am getting it wrong
Because this.http.post('${this.baseUrl}', activity); won't invoke service with the value of this.baseUrl, you can find out why according to the error message.
The URL you passed to post is still a string not a variable.
Please modify service.ts as follows:
...
return this.http.post(this.baseUrl, activity);
}
UPDATE
Another problem is your service consumes request parameters, so you have to pass these URL arguments for HTTP request in service.ts.
The valid URL should look like this:
http://localhost:8080/api/startreg?firstDate=XXX&secondDate=XXX&username=XXX
But I am not familar with TypeScript, so I don't know how to do this. Maybe you can refer to Angular2 - Http POST request parameters.
BTW, I strongly recommend that you should use #RequestBody rather than #RequestParam for your POST service.

API Connect 5 - Error attempting to read the urlopen response data

I'm trying to create a REST API from a SOAP Service using IBM API Connect 5. I have followed all the steps described in this guide (https://www.ibm.com/support/knowledgecenter/en/SSFS6T/com.ibm.apic.apionprem.doc/tutorial_apionprem_expose_SOAP.html).
So, after dragging the web service block from palette, ensuring the correctness of endpoint and publishing the API, I have tried to call the API from the browser. Unfortunately, the API return the following message:
<errorResponse>
<httpCode>500</httpCode>
<httpMessage>Internal Server Error</httpMessage>
<moreInformation>Error attempting to read the urlopen response
data</moreInformation>
</errorResponse>
To testing purpose, I have logged the request and I have tried the request on SOAPUI. The service return the response correctly.
What is the problem?
In my case, the problem was in the backend charset (Content-Type: text/xml;charset=iso-8859-1).
For example, backend returns text/xml in German (or French). Api Connect cannot process character ü. It needs Content-Type: text/xml;charset=UTF-8.
I had a similar issue, in my case was the accept. if you have an Invoke and the content-type or the accept, is not matching the one of the request, or the response that you got, APIC is getting mad.
Please, check if the formats to send (contentType) and receive (accept) are the same of that your API expected. In my case the error occurs because the API returns a String and my default code is configured to receive a JSON body.
//define a JSON-PLAIN TEXT protocol
private HttpEntity<String> httpEntityWithBody(Object objToParse){
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + "xxx token xxx");
headers.set("Accept", MediaType.TEXT_PLAIN_VALUE);
headers.setContentType(MediaType.APPLICATION_JSON);
Gson gson = new GsonBuilder().create();
String json = gson.toJson(objToParse);
HttpEntity<String> httpEntity = new HttpEntity<String>(json, headers);
return httpEntity;
}
//calling the API to APIC...
ParameterizedTypeReference<String> responseType = new
ParameterizedTypeReference<String>(){};
ResponseEntity<String> result =
rest.exchange(builder.buildAndExpand(urlParams).toUri(), HttpMethod.PUT, httpEntityWithBody(myDTO), responseType);
String statusCode = result.getStatusCodeValue();
String message = result.getBody();

Apache HTTPClient Headers are not correctly set

i'm trying to request a GET via HTTPS trough a Proxy. The Proxy answers with 400:Bad Request. I sniffed the data with wireshark and i have seen, that the headers are not set. Because of security, i replaced some Values with <> Brackets. Can anybody help?
This is a part of my implementation:
String urlString = ctx.getUrl();
HttpHost target;
CloseableHttpClient httpclient;
HttpClientContext localContext;
try
{
CredentialsProvider credsProvider = new BasicCredentialsProvider();
int proxyport = Integer.parseInt(ctx.getProxyPort());
credsProvider.setCredentials(
new AuthScope(<MyProxyUrl>, <MyProxyPort>),
new UsernamePasswordCredentials(<MyProxyUser>, <MyProxyPassword>));
httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
target = new HttpHost(urlString, 443, "https");
HttpHost proxy = new HttpHost(<MyProxyUser>, <MyProxyPassword>);
RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
request = new HttpGet("/");
request.setURI(new URI(urlString));
//this method sets different header
HttpProperty.setHeaders(request, ctx);
request.setConfig(config);
HttpResponse response = httpclient.execute(target, request);
I have traced the headers in the request with and printed name/value with the output below:
Header[] headers = request.getAllHeaders();
Header Name:Proxy-Connection
Header Value:close
Header Name:Proxy-Authorization
Header Value:Basic
Header Name:User-Agent
Header Value: MyDevice
Header Name:Accept
Header Value:text/html
At least this is the response:
Content length responesCode: 0 400
From Wireshark sniffing i found, that the headers which are defintly inside the request are not set when sending CONNECT.
I attached this picture:
EDIT:
Thank you Damian Nikodem,
but i found the solution.
The first request is always sent without user headers.
I changed two things, and the proxy authorization works:
request = new HttpGet(urlString);
HttpResponse response = httpclient.execute(request);
I am assuming that you are attempting to communicate with a SCADA or production management system. From what I can see you are sending plain HTTP to your target server via the proxy, while trying to connect via HTTPS.
I couldn't see the response in your wireshark dump, but it most likely contains a error message that looks something like this:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>400 Bad Request</title>
</head>
<body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
Reason: You're speaking plain HTTP to an SSL-enabled server port.<br />
Instead use the HTTPS scheme to access this URL, please.<br />
<blockquote>Hint: <b>https://???/</b></blockquote>
</p>
</body>
</html>
P.S. You should edit your image a little bit more because it shows a LOT of information about your employer/customer..
#Thorgas, I don't understand what you sad about "found the solution". Do you mean that you found out how to add extra headers in the CONNECT with HttpClinet? I'm also confusing about this.
But i found out that using HttpsUrlconnection in android doesn't have this kind of problem.
URLConnection urlConnection = url.openConnection(proxy);
HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) urlConnection;
httpsUrlConnection.setRequestMethod("GET");
httpsUrlConnection.setRequestProperty("HEADER1","HEADER1Content");
httpsUrlConnection.connect();

Send Http Request via JScript

I got a href from Website by inspect it, and I would like to send http request to update the value. But unfortunately the value isn't updated. And response text is the login page.
The href as below.
<a href="SystemTeam.do?formPostType=Update&ID=001&toggle=false">
My JScript as below.
var baseURL =
"https://xx.xx.xx.xx/admin/SystemTeam.do?formPostType=Update&ID=001&toggle=true";
var xmlHttpRequest = new ActiveXObject("MSXML2.ServerXMLHTTP.3.0");
//Ignore SSL error.
xmlHttpRequest.setOption(2,13056);
xmlHttpRequest.open("GET", baseURL, false);
//Set login user authorization
xmlHttpRequest.setRequestHeader("Authorization", "Basic XXXXX");
xmlHttpRequest.send();
Could anyone give some suggestions?

Using Google's ClientLogin Interface via XMLHttpRequest in Javascript

I am trying to learn the ClientLogin Interface detailed on the Account Authentication APIs on Google code website.
I am using Firefox 3.5pre (Shiretoko) and XMLHttpRequest object in Javascript to follow the process. Here's a stripped down version of what I have:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
//<![CDATA[
function update() {
var auth_params = "accountType=HOSTED_OR_GOOGLE&Email=val"
+"&passwd=val&service=cl&source=MMA-Learning";
var request = new XMLHttpRequest();
request.open('POST', 'https://www.google.com/accounts/ClientLogin', true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-Length", auth_params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
alert ("Request done");
}
};
try {
request.send( auth_params );
} catch (e) {
alert ("Send Exception:\n"+e);
}
}
//]]>
</script>
</head>
<body>
Authenticate
</body>
</html>
When I click on the Authenticate link, all I get back is a Bad Request response. Examining the request headers, I don't see Content-Type set to application/x-www-form-urlencoded.
I am using Firebug 1.5X to examine the traffic.
For now, all I want to do is generate request mentioned in the Sample Request section and get a response mentioned in the Sample Responses section. If I get there, I want to get some account specific data like, unread Google Reader feeds etc.
I suspect that you've been bitten by Javascript's "same origin" policy. It prevents Javascript, including XmlHttpRequest, from accessing one domain from another. More information is available from Mozilla.
There are hacks to get around this, but I have no idea if they'll work with Google's API.
the 'p' in 'passwd' is a small 'p' instead of a capital 'P'
you probably figured that out tho. When you post and you find the answer, it is always polite if you post the answer as well. This helps the people in the future who will look at your post for information
That 'p' took me two hours to find because i persummed that the code google gave was copied correctely and there was no case mistakes
no point in Internet being full of questions with no answers