How to get body content from request in mobile service in Azure - azure

I crate a mobile service and also a custom api for that in Azure. I use fiddler to send request and do some basic and simple testing.
At Azure side, I create a custom api for my mobile service. Let say the name is ExampleCustomApi. And in the code I have
exports.put = function(request, response) {
var tags = request.parameters.tags;
...
...
}
At fiddler side, I set http method to "PUT" and the url to my custom api.
Then I set a request body to { "tags": "tag1" }.
When I execute the request in fiddler, I receive 500 back. The log in Azure's mobile service says that parameters is undefined.
My question, then, is how to get the request body at the server side. I look at the document of request object, it seems to me that parameters is the one I should use, but it doesn't work.

request is an object in express.js library.
This is the documentation from MSDN http://msdn.microsoft.com/library/azure/jj554218.aspx
the documentation from express.js http://expressjs.com/api.html#req.body
And I can use request.body to get the body content.

After many attempts we cracked getting the content from a weburl. Hope this helps :) Jsonbody would hold your page content. This is a copy where we pulled json from one of our API's
var message = "try";
var jsonBody = "";
var request = require('request');
request.get({
url: "https://superduperwebaddress.com/api/pull"},
function(error,response,body){
if(!error)
{
var mybody = JSON.parse(body);
jsonBody = mybody;
console.warn("we are here well");
}else{
console.error(error);
}
}
);

Related

validateRequest method in Node.js Twilio client library not validating request while running in AWS Lambda

I am trying to validate that an http POST request to an AWS Lamdbda function URL from a Twilio HTTP Request widget inside a Twilio Studio flow truly originated from Twilio. I am using the Node.js Twilio client library, which provides the validateRequest method to accomplish what I am after. The content-type header in the Twilio Studio flows HTTP Request widget is set to application/json
The problem is that I am passing in the "x-twilio-signature" header, the url, twilio auth token, and POST params to the validateRequest method and it always returns false. Below is the code snippet used to try and accomplish this.
const authToken = process.env.twilio_auth_token
const sid = process.env.twilio_account_sid
const client = require('twilio')
exports.handler = (event) =>
{
let twilioSignature = event.headers['x-twilio-signature']
let requestBody = event.body
let requestUrl = 'https://my-function-url.io/'
let requestIsValid = client.validateRequest(authToken, twilioSignature, requestUrl, requestBody)
if(requestIsValid){
console.log('valid request')
} else {
console.log('invalid request')
}
}
Seems like someone else had a similar issue in the past. I copied parts of the answer here:
The issue here is that query string parameters are treated differently to POST body parameters when generating the signature.
Notably part 3 of the steps used to generate the request signature says:
If your request is a POST, Twilio takes all the POST fields, sorts them by alphabetically by their name, and concatenates the parameter name and value to the end of the URL (with no delimiter).

Parsing request body prohibits request signature verification

I'm trying to build a serverless Slackbot using Lambda function. I end up with an error while verifying the Request URL through the Slack event API. #slack/events-api is the dependency that I'm using to capture the slack events.
Here is my code.
const sls = require('serverless-http');
const { createEventAdapter } = require('#slack/events-api');
require('dotenv').config();
const { SLACK_SIGNING_SECRET } = process.env
const slackEvents = createEventAdapter( SLACK_SIGNING_SECRET || '' );
slackEvents.on('message', async event => {
console.log('received!')
});
module.exports.server = sls(slackEvents.requestListener());
This is the error that I'm getting while verifing the request url
Slack Request URL verification
Can someone help me with this?
Just ran into this exact issue, and took a look into http-handler.js in node-slack-events.
All we have to do is store the raw request body as rawBody before serverless-http parses it.
serverless-http lets you transform the request, before it is sent to the app—great opportunity for a fix:
module.exports.handler = serverless(app, {
request(request) {
request.rawBody = request.body;
},
});
I'm not sure how to solve your problem exactly, but I do know what's causing it.
The library you're using, serverless-http parses the JSON body sent by Slack. This causes an error to be thrown, because the slack-api-sdk expects to parse the raw request body itself.
Could you try removing serverless-http and just respond to the API Gateway event?

How to log the actual request header when using fetch API

Beginner question, I am using the fetch API in one of my Cloudflare Service Worker to send request to a third party; Everything works fine that I am able to send out the request and receive response; But now I have a need to log everything I sent and received, which I am not sure how exactly can I do so;
The main requirement:
Able to log the whole request header being sent
The problem is that the request header that I specified is not the full header being sent, like in the following example I only specified the content-type, but in real practice it will send with more properties added by the application itself, e.g. accept, x-forwarded-for, content-length, etc.
Request:
var toThirdPartyReqMethod = 'POST';
var toThirdPartyReqHeader = {'content-type': 'application/json'};
var toThirdPartyReqSetting = {
method: toThirdPartyReqMethod,
headers: toThirdPartyReqHeader,
body: toThirdPartyReqBodyArrayBuffer
};
var toThirdPartyUrl = "https://somewhere.com";
var fromThirdPartyResponse = await fetch(toThirdPartyUrl, toThirdPartyReqSetting)
var fromThirdPartyResponseBodyArrayBuffer = await fromThirdPartyResponse.arrayBuffer();
I am able to use fromThirdPartyResponse to digest the response; but I have no idea how to record the exact request I sent out.
I tried to do it as follows:
var oriReqHeaderContentType = fromThirdPartyResponse.request.headers.get("content-type");
But obviously it is not the right answer and returned with the following error:
TypeError: Cannot read property 'headers' of undefined
Anyone gets some idea of how to log the request being sent when using fetch API?
Sorry for asking beginner questions :(
You can access request headers like this
const contentType = req.get("Content-Type");

How to map SOAP request with SOAP response using node-soap

I use node-soap to manage SOAP requests/responses on server side. I'm using server.log function to log requests and responses and I need to somehow map them (connect) to know which request caused a certain response.
See the code sample:
function log(type, data) {
let logId = '';
if (type === 'received') {
// On received I need to generate logId
logId = generateLogId();
console.log(logId, data);
}
if (type === 'replied') {
// On replied I need to get the logId that was generated on the matching request
logId = getLogId();
console.log(logId, data);
}
}
I've tried using node's continuation-local-storage, but without much success.
Help me, Obi-Wan Kenobi. You're my only hope.

Creating Stripe Express Connect Account, Getting 'unsupported_content_type' when POST to endpoint for account ID

Im having trouble sending "POST" request to stripes token endpoint at the end of creating connect express account. Currently, my application(ios) is opening the OAuth Link (which contains a redirect uri to my server(Firebase functions)) to the express account creation web page made by stripe. Once the user completes their account set up I receive the authorization code in the backend and then use the authorization code and client_secret_key to send a POST request to "https://connect.stripe.com/oauth/token". I'm using XMLHttpRequest npm to send a POST request within firebase functions and setting my parameters like this
var params = "client_secret=" + CLIENT_SECRET + "&code=" + AUTHORIZATION_CODE + "&grant_type=authorization_code"
and my request header like this
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
Yet I get back this error after sending POST request
"error": {
"type": "invalid_request_error",
"code": "unsupported_content_type",
"message": "Invalid request: unsupported Content-Type text/plain;charset=UTF-8. If error persists and you need assistance, please contact support#stripe.com."
}
I thought I was properly setting request header content-type to "application/x-www-form-urlencoded" but still getting back error as if the content-type was "Text/plain".
Here is full backend code
exports.CreateUsersPayoutAccount = functions.https.onRequest((req, res) =>{
const userID = req.query.state
const AUTHORIZATION_CODE = req.query.code
console.log(userID)
console.log(AUTHORIZATION_CODE)
//console.log(req);
var request = new XMLHttpRequest()
request.addEventListener('load', getStripeConnectUserID)
var params = "client_secret=" + CLIENT_SECRET + "&code=" + AUTHORIZATION_CODE + "&grant_type=authorization_code"
//var params = JSON.stringify({client_secret : CLIENT_SECRET, code : AUTHORIZATION_CODE, grant_type : "authorization_code"})
console.log(params);
request.open("POST", "https://connect.stripe.com/oauth/token", true)
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
//request.setRequestHeader("Content-length", params.length)
request.send(params)
})
If anyone could point me in the right direction it would be much appreciated, I am somewhat new to writing backend HTTP calls.
In the backend cloud function, rather than attempt to send the POST request from there, write the auth code to a spot in firebase database.
Back in Xcode have a listener function that executes if there's a change in that database spot. The function should then read the change (the auth code) and simply send an easy swifty POST request with Alamofire.
I understand why you made the uri direct to your specific cloud function (since its an http trigger), but isn't the point of sending a uri so that stripe can redirect the user back to a specific app page, does the user still get directed back to the app in your case???

Resources