csrf token validation fail in post request while calling sap odata service - node.js

var Array = require('node-array');
var request = require("request");
username = "user24",
password = "",
auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var options = { method: 'GET',
url: "http://207.188.73.88:8000/sap/opu/odata/sap/ZTEE_SUGGEST_SRV/ZteeSuggestSet?$filter=Number eq 5 and Date eq datetime'2014-03-11T00%3A00%3A00'&$format=json",
headers:
{
i am fetching xcsrf token here
'x-csrf-token': 'fetch',
'content-type': 'application/json',
authorization: auth } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
// console.log(response.headers['x-csrf-token']);
var token="'";
token+=response.headers['x-csrf-token'];
token+="'";
//console.log(token);
var options = { method: 'POST',
url: 'http://207.188.73.88:8000/sap/opu/odata/sap/ZTEE_TIME_SRV/ZTEERESERVESet',
and setting the csrf token here but it give me error that scrf token required or invalid
headers:
{
authorization: auth,
'x-csrf-token': token,
'content-type': 'application/json' },
body:
{ Time: 'time\'PT11H00M00S\'',
Date: 'datetime\'2014-03-11T00%3A00%3A00\'',
Location: 'AAJ',
Number: 3 },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
// console.log(body);
here it shows that token rrequired but i am already setting that in header
console.log(response.headers['x-csrf-token']);
});
});

I had faced similar situation while working with SAP WEBIDE.
I had disabled the request for token and i was able to establish the connection with Odata services. I did something like this code snippet in my component.js file.
var oModel = new sap.ui.model.odata.ODataModel(this.getMetadata().getConfig().serviceUrl);
oModel.disableHeadRequestForToken = true;
serviceURL contained the URL to Odata Service.
You can try to disable the CSRF token request and check.

Related

Search Contacts with SendGrid API

https://sendgrid.api-docs.io/v3.0/contacts/search-contacts
I'm attempting to search for a contact as shown in SendGrids docs above. In the body section below I'd like to change the hard coded "andrew#gmail.com" to be a variable. Such as email = req.user.email; What is the correct way to do that? Just setting the variable and dropping in 'email' does not work.
var request = require("request");
var options = { method: 'POST',
url: 'https://api.sendgrid.com/v3/marketing/contacts/search',
headers:
{ 'content-type': 'application/json',
authorization: 'Bearer SG.key' },
body: { query: 'email LIKE \'andrew#gmail.com\' AND CONTAINS(list_ids, \'6bcc2d0c-ea17-41ba-a4a1-962badsasdas1\')' },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
Twilio SendGrid developer evangelist here.
Try using string interpolation using back ticks (which, as an added bonus, means you don't have to escape your single quotes), like below:
const email = req.user.email;
const body = `email LIKE '${email}' AND CONTAINS(list_ids, '6bcc2d0c-ea17-41ba-a4a1-962badsasdas1')`;
const options = {
method: 'POST',
url: 'https://api.sendgrid.com/v3/marketing/contacts/search',
headers: {
'content-type': 'application/json',
authorization: 'Bearer SG.key'
},
body: { query: query },
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});

How to do a GET request with node.js passing a JWT token in header

I have been trying to do a GET request to my server which has is running locally on port 4000.
I generate a JWT token and pass it in the header as follows
var request = require('request');
var options = {
'method': 'GET',
'url': 'localhost:4000',
'headers': {
'JWT': '<JWT PASTED HERE>',
'Content-Type': 'application/json'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
But I keep getting
{"errors":[{"title":"invalid_request","id":"Requesting stuff","meta":{"server-time":1591980353},"errorCode":"bad-request","status":400,"detail":"This JWT has invalid path parameter"}],"error_description":"This JWT has invalid path parameter","error":"invalid_request"}
My JWT is correctly created, I verified it in https://jwt.io/
Is it because 'request' module is deprecated in node.js?
Is there another way I can achieve the below?
Try this one
var request = require('request');
var options = {
'method': 'GET',
'url': 'localhost:4000',
'headers': {
'Authorization': 'Bearer <JWT PASTED HERE>',
'Content-Type': 'application/json'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
or
var options = {
'method': 'GET',
'url': 'localhost:4000',
'headers': {
'Authorization': 'JWT <JWT PASTED HERE>',
'Content-Type': 'application/json'
}
};
Bearer or JWT depends how it is defined in backend

how to authenticate to oracle cloud ipnetwork API using auth token?

I am unable to authenticate to oracle cloud using auth token.I am using "request" node module in node js to connect to oracle cloud using its REST endpoint.I am passing the authentication token in header and the response i am getting is"HTTP 401 Unauthorised".Dont know why it is happening.Any help is appreciated.
Here's an example that first obtains a token and then uses it for a subsequent request.
Start by setting these environment variables:
OC_REST_ENDPOINT
OC_IDENTITY_DOMAIN
OC_USER
OC_PASSWORD
For example:
export OC_REST_ENDPOINT=https://api-z999.compute.us0.oraclecloud.com/
export OC_IDENTITY_DOMAIN=myIdentityDomain
export OC_USER=some.user
export OC_PASSWORD=supersecretpassword
Then use the following example:
const request = require('request');
const restEndpoint = process.env.OC_REST_ENDPOINT;
const identityDomain = process.env.OC_IDENTITY_DOMAIN;
const user = process.env.OC_USER;
const password = process.env.OC_PASSWORD;
request(
{
method: 'POST',
uri: restEndpoint + 'authenticate/',
headers: {
'content-type': 'application/oracle-compute-v3+json',
},
body: JSON.stringify({ // Must be a string, buffer or read stream
user: '/Compute-' + identityDomain + '/' + user,
password: password
})
},
function(err, res, body) {
if (err) {
console.log(err);
return;
}
if (res.statusCode !== 204) {
console.log('Something broke.');
return;
}
console.log('Got auth token');
let token = res.headers['set-cookie'][0];
request(
{
method: 'GET',
uri: restEndpoint + 'instance/',
headers: {
'accept': 'application/oracle-compute-v3+directory+json',
'cookie': token
}
},
function(err, res, body) {
if (err) {
console.log(err);
return;
}
console.log(body);
}
);
}
);

CSRF token validation failed in nodejs while posting data to odata service

var request = require('request');
var username = '';
var password = '';
var url = 'http://207.188.73.88:8000/sap/opu/odata/sap/ZTEE_TIME_SRV/ZTEERESERVESet(Time=time\'PT11H00M00S\',Date=datetime\'2014-03-11T00%3A00%3A00\',Location=\'TAJ\',Number=3)';
var auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');
// i am trying to post data to odata service but the problem is that i could not get valid token from get service to use it in the post method i am first send get method
request(
{
url: url,
headers: {
'Authorization': auth,
'x-csrf-token': 'Fetch',
},
},
function(error, response, body) {
console.log('JSON data ' + response);
console.log('body' + body);
// trying to get the token to use in post
console.log(response.headers);
request(
{
url: url,
headers: {
here it says invalid token
'Authorization': auth,
'X-CSRF-TOKEN': 'u6piLO58XoK6udOkQ5Naww==',
},
method: 'POST',
//Lets post the following key/values as form
form: {
Time: 'PT11H00M00S',
Date: '2014-03-11T00%3A00%3A00',
Location: 'TAJ',
Number: 3,
},
},
function(error, response, body) {
console.log(body);
},
);
},
);
I got the solution.
I was trying to do this with POSTMAN, and it was working fine.
The thing is that when i was asking for CSRF token it always gave me the same back.
But when i tried with node, every time was different. Then i realized that the cookie was missing.
And thats all, the solution is to send the cookie at least in POST requests.
The set-cookie of the "Fetch" request must be sent in the Post request as Cookie beside the x-csrf-token
I put the example in typescript, but in js doesnt change so much, the idea is the same.
The example is not the best case but is complete to figure out how it works
let headers = {
"Authorization": "Basic " + new Buffer(username + ":" + password).toString("base64"),
"Content-Type":"application/json",
"Accept":"application/json",
"x-csrf-token":"Fetch" // get CSRF Token for post or update
};
// if you are using session vars
if (req.session.headers && req.session.headers.cookie) {
headers['Cookie'] = req.session.headers.cookie;
} else {
req.session.headers = {}; // initialize as object
}
let opts = {
url: "https://{host}:{port}/sap/opu/odata/sap/MD_SUPPLIER_MASTER_SRV",
qs: params1, // params set before, not set in the example
headers: headers,
json: true,
}
request(opts, (error: any, response: any, body: any): any => {
if (!error && response.statusCode === 200) {
if (response.headers["set-cookie"]) {
req.session.headers.cookie = response.headers["set-cookie"]; // store Cookie in session
headers['Cookie'] = req.session.headers.cookie; // set in headers for the next call. I guess this is the part you missed
}
if (response.headers['x-csrf-token']) {
req.session.headers.csrf = response.headers['x-csrf-token']; // store csrf-token in session
headers['x-csrf-token'] = req.session.headers.csrf; // set in headers for the next call
}
let options: request.Options = {
url: "https://{host}:{port}/sap/opu/odata/sap/MD_SUPPLIER_MASTER_SRV/C_BusinessPartnerSupplierEdit",
method: 'POST',
headers: headers,
qs: params2, // params set before
json: true,
}
request(options, (error: any, response: any, body: any): any => {
res.json(body);
});
}
});
Regards

oAuth code exchange for secret token

I'm making an app that is supposed to use oAuth to authenticate players from the Blizzard servers, I want to access their character info.. and I can't figure out how to ask for the secret_token. I guess I'm doing my post request wrong below is the code I'm using
app.post('/', function(req, res) {
var code = req.body.code; //this is the code i get ounce the player is redirected back to my redirect_uri
var redirectUri = "https://localhost:3000/oauth_callback.html";
var scope = "wow.profile";
var key = "they client_id i was given";
var secret = "they secret I was given";
var grantType = "authorization_code";
var tokenUri = "https://us.battle.net/oauth/token";
var uriBody = "?client_id=" + key + "&client_secret=" + secret + "&grant_type=authorization_code&code=" + code + "&redirect_uri=" + redirectUri + "&scope=" + scope;
request({
url: tokenUri, //URL to hit
method: 'POST',
headers: {
'Content-Type': "application/x-www-form-urlencoded",
},
body: uriBody //Set the body as a string
}, function(error, response, body){
if(error) {
console.log(error);
} else {
console.log(response.statusCode, body);
}
});
so basically I'm getting the code making a post request to my server with it, and then triggering a post request to the blizzard server trying to exchange my code for an access token.
The error I get is:
401 '{"error":"unauthorized","error_description":"An Authentication object was not found in the SecurityContext"}'
I'm using Node.js & request.js to make the post, my guess is I'm not making a proper request post request?
I think body key is not acceptable in request.
Send data in json if content-type is JSON or form if content-type is x-www-form-urlencoded
Like this
request({
url: tokenUri, //URL to hit
method: 'POST',
headers: {
'Content-Type': "application/x-www-form-urlencoded",
},
form: uriBody //Set the body as a string
}, function(error, response, body){
if(error) {
console.log(error);
} else {
console.log(response.statusCode, body);
}
});
finally! here is how I got it to work!
qs = query-string.js library...
var token_params = qs.stringify({
client_id: key,
client_secret: secret,
code: code,
scope: scope,
grant_type: 'authorization_code',
redirect_uri: redirectUri
});
request('https://us.battle.net/oauth/token?' + token_params, function(error, response, body){
if (error) {
console.log(error);
} else {
console.log(body)
}
});

Resources