How to call a https POST method using gatewayscript in IBM Bluemix APIConnect - https

I am trying to call another API inside Bluemix or any other HTTPS post method using a gateway script inside IBM Bluemix (API Connect) using the code below:
var urlopen = require('urlopen');
var options = {
target: 'https://pokemons.mybluemix.net/api/pokemons/1',
method: 'POST',
headers: {},
contentType: 'application/json',
timeout: 60,
data: {"Message": "DataPower GatewayScript"}
};
urlopen.open(options, function(error, response) {
if (error) {
// an error occurred during the request sending or response header parsing
session.output.write("urlopen error: "+JSON.stringify(error));
} else {
// get the response status code
var responseStatusCode = response.statusCode;
var responseReasonPhrase = response.reasonPhrase;
console.log("Response status code: " + responseStatusCode);
console.log("Response reason phrase: " + responseReasonPhrase);
// reading response data
response.readAsBuffer(function(error, responseData){
if (error){
throw error ;
} else {
session.output.write(responseData) ;
apim.output('application/json');
}
});
}
});
But I am getting the following error:
{
"httpCode": "500",
"httpMessage": "Internal Server Error",
"moreInformation": "URL open: Cannot create connection to 'https://pokemons.mybluemix.net/api/pokemons/1', status code: 7"
}
Looks like there is some issue with the SSL Connections. If so, how can I get the SSL Details for the default Sandbox Catalog in IBM Bluemix API Connect? Or, how can I make the HTTPS POST calls to the above sample URL?

Since Version 5.0.6:
IBM API Connect 5.0.x
Forward SSLProxy (and Crypto) is replaced with SSLClient. These new profiles support ephemeral ciphers (DHE and ECDHE), perfect forward secrecy, and Server Name Indication (SNI) extension. Note that DHE ciphers in DataPower SSLServerProfile use 2048-bit DH parameters (as server) and accept 1024-bit DH parameters (as client).
In order for you specific example to work on API Connect using HTTPS you need to specify the sslClientProfile.
For example:
var urlopen = require('urlopen');
var options = {
target: 'https://pokemons.mybluemix.net/api/pokemons/1',
method: 'POST',
headers: {},
contentType: 'application/json',
timeout: 60,
sslClientProfile: 'webapi-sslcli-mgmt',
data: {"Message": "DataPower GatewayScript"}
};

Related

Handling base64 string as application/pdf for a single endpoint on API Gateway

We have an API that has multiple different endpoints, as you'd expect. We have the requirement to add a new endpoint which will return an application/pdf along with the file data.
To do this, we return the following:
return {
statusCode: 200,
headers: {
'Content-Type': 'application/pdf',
'Content-disposition': `attachment; filename=${filename}.pdf`,
'Accept': 'application/pdf',
},
body: fileData,
isBase64Encoded: true,
};
The isBase64Encoded only works when a binary media type is set in the API Gateway. As detailed here:
https://medium.com/#ngchiwang/aws-api-gateway-lambda-return-binary-image-ba8faa660839
The issue we have is that by setting the binary media type to * / * (no spaces) on the API Gateway, this, in turn, affects all other endpoints on the API.
Example This breaks one endpoint on the OPTIONS cors check, returning an InternalServerErrorException without reason. This endpoint is just a GET with no data in the request.
Does this mean we need a separate API just for this one endpoint, or is there a way we can include this in the same APIG?
For further clarification, this is a POST that includes a small amount of JSON in the request: {"someValue":1234} and returns the above application/pdf content type.
I'm just tackling this issue and resolved it like this:
Send base 64 string just as normal json response and handle the pdf part on the client
const sendRes = (status:number, body:any) => {
var response = { statusCode: status, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) };
return response;
};
return sendRes(201, {pdf:your-base64-string} );
Then on the client (Nuxt in my case):
let res = await this.$store.dispatch('pdf/makePdf')
const linkSource = `data:application/pdf;base64,${res.data.pdf}`;
const downloadLink = document.createElement("a");
const fileName = "your-pdf-filename.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
This open a download window and lets you save the file locally

How come I keep getting a "Request failed with response code 401" when trying to push via Urban Airship?

I have double, triple, and quadruple checked that I have the right master key that I'm passing. My parameters are taking directly from the UA website also so it can't be that. Anyone see what I'm doing wrong here???
Parse.Cloud.define("sendPush", function(request, response) {
var Buffer = require('buffer').Buffer;
var parameters = {
"audience" : "all",
"device_types" : "all",
"notification" : {
"alert" : "Hello from Urban Airship."
}
};
var params = JSON.stringify(parameters);
Parse.Cloud.httpRequest({
url: "https://go.urbanairship.com/api/push/",
method: 'POST',
headers: {
"Content-Type" : "application/json",
"Authorization" : 'Basic ' + new Buffer('MASTER_KEY').toString('base64'),
"Accept" : "application/vnd.urbanairship+json; version=3;"
},
body: params,
success: function(httpResponse) {
response.error(httpResponse);
},
error: function(httpResponse) {
response.error('Request failed with response code ' + httpResponse.status);
}
});
});
I've also tried adding in APP_SECRET:
"Authorization" : 'Basic ' + new Buffer('APP_SECRET':'MASTER_KEY').toString('base64'),
It's not clear from your code sample if you are including the app key in your request. API requests to Urban Airship use HTTP basic authentication. The username portion is the application key and the password portion in this case is the master secret. The application secret is restricted to lower-security APIs and is for use in the distributed application. The master secret is needed for sending messages and other server API requests.
Urban Airship provides a guide for troubleshooting common API issues.
I had the same problem and tried to figure it out by Network diagnosing tools for more than two days. Because after debugging I checked that I send the right credentials to UA. After all I called the UA and ask them to check the Credentials (in my case was appKey and appToken for streaming with java-connect API) if they are still valid. They checked and approved the validation but just in case sent me a new credentials. And I could connect with the new credentials!
It is for sure a bug by UA because I tested the whole time by another test application, which was a Desktop java application and I could connect to the server (with the same appKey and appToken) and get the events, but I got 401 error in my main Application, which was a Web Application running on TomCat 8.0 . It means It worked in a same time in with the same credential for one application and did not work for another application.

Figuring out who has authenticated with basicAuth on Node while processing a POST request

I am using basicAuth to authenticate POSTs on a specific address.
On the client side I am using a command of the form:
$.ajax({
type: "POST",
accepts: "text/plain",
url: "http://localhost:3000/somewhere",
data: JSON.stringify(something),
contentType: "application/json; charset=UTF-8",
dataType: "json",
success: function(data) {
window.alert("Received back: '" + data + "'");
},
username: theUsername,
password: "a password"
});
This is working fine, in the sense that the username stored in theUsername passes the authentication mechanism that I have on node. While the user is authenticated I can print a console.log statement and see who has actually authenticated (I am not validating the password at the moment). But then the actual processing starts for the POST request. However, at that point how can I figure out the username and the password used in the original request? I tried to look on the headers of the request but I don't see anything there.
When you receive a Basic authentication request you should be able to read the "authorization" header in req.headers.authorization You have to pull out the the base64 encoded credentials and then decode them. Presumably, in Express you use req.header("authorization") or req.get("authorization")
For a standalone example, take a look at https://gist.github.com/charlesdaniel/1686663 which I have copied underneath for future reference
var http = require('http');
var server = http.createServer(function(req, res) {
// console.log(req); // debug dump the request
// If they pass in a basic auth credential it'll be in a header called "Authorization" (note NodeJS lowercases the names of headers in its request object)
var auth = req.headers['authorization']; // auth is in base64(username:password) so we need to decode the base64
console.log("Authorization Header is: ", auth);
if(!auth) { // No Authorization header was passed in so it's the first time the browser hit us
// Sending a 401 will require authentication, we need to send the 'WWW-Authenticate' to tell them the sort of authentication to use
// Basic auth is quite literally the easiest and least secure, it simply gives back base64( username + ":" + password ) from the browser
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="Secure Area"');
res.end('<html><body>Need some creds son</body></html>');
}
else if(auth) { // The Authorization was passed in so now we validate it
var tmp = auth.split(' '); // Split on a space, the original auth looks like "Basic Y2hhcmxlczoxMjM0NQ==" and we need the 2nd part
var buf = new Buffer(tmp[1], 'base64'); // create a buffer and tell it the data coming in is base64
var plain_auth = buf.toString(); // read it back out as a string
console.log("Decoded Authorization ", plain_auth);
// At this point plain_auth = "username:password"
var creds = plain_auth.split(':'); // split on a ':'
var username = creds[0];
var password = creds[1];
if((username == 'hack') && (password == 'thegibson')) { // Is the username/password correct?
res.statusCode = 200; // OK
res.end('<html><body>Congratulations you just hax0rd teh Gibson!</body></html>');
}
else {
res.statusCode = 401; // Force them to retry authentication
res.setHeader('WWW-Authenticate', 'Basic realm="Secure Area"');
// res.statusCode = 403; // or alternatively just reject them altogether with a 403 Forbidden
res.end('<html><body>You shall not pass</body></html>');
}
}
});
server.listen(5000, function() { console.log("Server Listening on http://localhost:5000/"); });

xhr sending requests to specific port?

I am very new to ajax development, I am trying to use xhr to get and post data,the problem is when I use port based requests?
here is my working code and not working codes
$.ajax({
url : "login.php",
type : "post",
data : {
userProfile : JSON.stringify(data)
},
success : handleDBResponse,
error : function(jqXHR, textStatus,errorThrown) {
console.log("The following error occured: "+ textStatus,errorThrown);
},
complete : function() {
// console.log("user authentication
// successful.")
}
});
this works good, but when I am using native xhr with url:port getting no response.
function reqListener () {
console.log(this.responseText);
};
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "http://www.domain.com:443/akorp.css", true);
oReq.send();
It's not working, I was debugged and I found request status is cancelled.
.htaccess file included
Access-Control-Allow-Origin:*
still I am getting the error
www.domain.com:443 not allowed by www.domain.com Access-Control-Allow-Origin etc..
what are the possible causes for this error and how to properly send request to port?
443 is the HTTPS port. Perhaps you should try an HTTPS URL instead of forcing the port.
I'm not sure I want to know why you're pulling a CSS file from somebody else's serer with xhr.

AJAX 504 when calling ASP.NET Web API

My AJAX call is returning a 504 error when calling an ASP.NET Web API action.
More info:
Here's my API action:
public HttpResponseMessage Get(string fileName, int feedID)
{
try
{
// create file...
return new HttpResponseMessage { Content = new StringContent("Complete."), StatusCode = HttpStatusCode.OK };
}
catch (Exception ex)
{
Log.WriteError(ex);
throw new HttpResponseException(new HttpResponseMessage
{
StatusCode = HttpStatusCode.InternalServerError,
Content = new StringContent("An error has occurred.")
});
}
}
Here's my AJAX call:
$.ajax({
url: url,
type: 'GET',
success: function () {
$("#lblProgressDownload").hide();
window.open("Previews/" + fileName);
},
error: function (xhr, status, error) {
$("#lblProgressDownload").hide();
alert("Error downloading feed preview: " + error);
}
});
I get a 504 error (viewed in fiddler/ chrome console) when the file takes too long to create. The "error" parameter in the error callback doesn't return anything.
I only get the 504 error when it's hosted - on my dev it works fine.
How do I prevent this 504 error?
Note, I already tried changing the executionTimeout property in my web.config, as well as the ajax timeout. Neither worked.
HTTP error 504 is a gateway timeout:
The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI [...] in attempting to complete the request.
I suspect that means there is a proxy or gateway somewhere between you and the production server, but not your dev server, which is why it fails on the one but not the other.
Your choice is either to make your server code fast enough that it doesn't trigger the timeout, or get whoever is running the proxy server to relax their timeout restrictions (assuming it's something that you or your company controls).

Resources