Setting request header in $.ajax - .htaccess

I need to make a request to a site which has HT Access enable. The str below has the username:password
Below is the code I am using
var str='msft:sks*';
var bytes = Crypto.charenc.Binary.stringToBytes(str);
var base64 = Crypto.util.bytesToBase64(bytes);
var auth='BASIC '+base64;
$.ajax({
url : 'http://mft.sta.com/',
method : 'GET',
async:false,
beforeSend : function(req,settings) {
req.setRequestHeader('Authorization', auth);
}
});
I am getting 401 authentication required error in FireBug.
But when i tried in POSTER plugin I am able to get the response. I copied the value of 'auth' in the above function and set it in the requester header for the key 'Authorization' in POSTER and it is working like a charm. But failing in Firefox or IE.
Any possible solution or workarounds.
Thanks in Advance.

Related

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");

Get the response headers from redirect url using node.js

Objective:
Te get the response.headers when I get the status code as 302 from redirects uri response
Issue:
I did a bit of googling about an issue which i'm facing at my end about the Redirect URL returning 500 rather than the expected 302. I found the npm request() can be used for redirects. However I'm not able to get the response headers as it always returns 500. But when I used the API end points manually with Postman (with interceptors turned ON) along with body and headers, I was able to get 302 redirects. This is essentially used for Automation testing for API
request(
url: 'https://blah/blah',
client_id:'something.com.au'
redirect_uri:'http://something' // used for mobile app and so it is OK to be have a valid url
response_type :'code'
scope : 'ALLAPI',
Username : 'cxxx'
Password : 'ccxcxc'
headers : {
'Content-Type': 'application/x-www-form-urlencoded',
'followRedirect' : true
}, function (error, response) {
console.log('The response val is', response.statusCode);
});
Question:
Not sure if npm request can do the justice or Am I using request in-correctly or should I have to use axios/follow-redirects etc.. something like that. Please advise. If anyone can provide proper directions on this, it'll be really helpful
Thanks,
Brad
I met the same problem, needle works for me.
var needle = require('needle'),
url = 'https://www.ibm.com/common/ssi/cgi-bin/ssialias?htmlfid=GBE03831USEN&';;
needle.get(url, {follow_max: 5}, function(error, res) {
console.log(res.statusCode);
});
#all. I've resolved using form property but with using req.post() method which returned the statuscode as 302 with response headers. Thanks all once again.

Making a Post request to Github API for creating issue is not working

I have been trying to make this post request to the github api for the last couple of days, but unfortunately the response is coming back as "bad message"
here is the piece of code we are sending in the post request using https request in node -
This is the post data
var issueData = JSON.stringify({
"title":title,
"body":comment
});
This is the options file
var options = {
host: 'api.github.com',
path: '/repos/sohilpandya/katasohil/issues?access_token='+sessions.token,
headers: {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0',
},
method: 'POST'
};
This is the https request
var requestaddIssue = https.request(options, function(responseFromIssues){
responseFromIssues.setEncoding('utf8');
responseFromIssues.on('data', function(chunk){
console.log('>>>>chunk>>>>>',chunk);
issueBody += chunk;
});
responseFromIssues.on('end',function(issueBody){
console.log(issueBody);
});
});
requestaddIssue.write(issueData);
requestaddIssue.end();
I have tried another approach where the authentication token for the user is in the header as
'Authentication': 'OAuth '+ sessions.token (where we are storing token inside sessions)
But the chunk response always seems to come back with the following in the console log.
{
"message": "Not Found",
"documentation_url": "https://developer.github.com/v3/issues/#create-an-issue"
}
I have tried the same in apigee and it seems to work ok and returns to correct response. Hoping someone can find the minor error in the code above that is causing this bad message error.
Except the issueBody variable is not defined in the snippets you posted, the code is correct. I tried it using a personal access token.
The error you get appears because you need to add a scope with power to open issues.
I tried the repo and public_repo scopes and they are both working. Note that repo has access to private repositories. Here you can see the list of scopes.
If you're using OAuth, then you you should have an url looking like this:
https://github.com/login/oauth/authorize?client_id=<client-id>&scope=public_repo&redirect_uri=<redirect-uri>

Reddit api session cookie format?

I'm trying to use reddit api to login with a bot using node.js and request.js. I've managed to figure out that I need both the modhash and the session cookie that are returned from the /api/login request. I have accessed both with the following code:
request.post({
uri: 'http://www.reddit.com/api/login',
json: true,
headers: agentheader,
qs : logincreds
},function(err,response,body){
if(err){
throw err;
} else {
if(response.statusCode == 200){
mhash = body.json.data.modhash;
session_cookie = body.json.data.cookie;
console.log(body.json.data.cookie);
console.log("login OK, modhash: "+mhash);
console.log("Session cookie: "+session_cookie);
agentheader = {
'user-agent': 'base10bot made by /u/01011110',
'X-Modhash' : mhash,
'Cookie' : 'reddit_session='+session_cookie
};
...
and in that last bit I set the custom headers with the modhash and the cookie in the way that someone on /r/redditdev told me it should be done. The session cookie doesn't work at all without the "reddit_session=" part, but with it everything I do returns a 403 forbidden.
I'm pretty sure the "cookie" is formatted wrong because when I log it, it shows up as a numerical id, a time-stamp, and a hash all comma delimited. Can someone help me figure out the right way to send this cookie header? Everything I find on google is either using python requests or bash.
I guess you are not parsing body as JSON. Try this -
data = JSON.parse(body);
session_cookie = data.json.data.cookie;

Can I send a GET request with cookies in the headers in Node?

In a browser, if I send a GET request, the request will send the cookie in the meanwhile. Now I want to simulate a GET request from Node, then how to write the code?
Using the marvelous request library cookies are enabled by default. You can send your own like so (taken from the Github page):
var j = request.jar()
var cookie = request.cookie('your_cookie_here')
j.add(cookie)
request({url: 'http://www.google.com', jar: j}, function () {
request('http://images.google.com')
})
If you want to do it with the native http:request() method, you need to set the appropriate Set-Cookie headers (see an HTTP reference for what they should look like) in the headers member of the options argument; there are no specific methods in the native code for dealing with cookies. Refer to the source code in Mikeal's request library and or the cookieParser code in connect if you need concrete examples.
But Femi is almost certainly right: dealing with cookies is full of rather nitpicky details and you're almost always going to be better off using code that's already been written and, more importantly, tested. If you try to reinvent this particular wheel, you're likely to come up with code that seems to work most of the time, but occasionally and unpredicatably fails mysteriously.
var jar = request.jar();
const jwtSecret = fs.readFileSync(`${__dirname}/.ssh/id_rsa`, 'utf8');
const token = jwt.sign(jwtPayload, jwtSecret, settings);
jar.setCookie(`any-name=${token}`, 'http://localhost:12345/');
const options = {
method: 'GET',
url: 'http://localhost:12345',
jar,
json: true
};
request(options, handleResponse);

Resources