So here is the situation:
Background: I am developing a Chrome App (not extension) using javascript making XHR calls to a website.
On login, I am posing all the form data (username, password etc.) to the login url like this
var xhr = new XMLHttpRequest();
xhr.open("POST", 'http://somewebsite/Login.aspx', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.withCredentials = true;
xhr.onload = function (e) {
console.log('on load of login request');
console.log(xhr);
xhr.open('GET', 'http://somewebsite/STS/sts_default.asp', true);
xhr.withCredentials = true;
xhr.responseType = 'document';
xhr.onload = LogicFunction;
xhr.send();
};
var params = "txtUsername=user&txtPassword=password"
xhr.send(params);
What I assume is that once the login request get processed, while I am using the same xhr object it should use the cookies that been set from the previous response.
While actually what happened is the l/login.aspx gives me a 302 redirect. And on that redirection its using the credential cookies. while the xhr I initiated within the onload block doesn't have any cookie credentials thus get kicked out by server.
What should I do to carry this cookie credentials.
Thanks
Yes Guys. The way how I did to keep the cookies are right. The browser (at least in chrome) helps to keep all the cookies that set by server. The only problem that I have was a 302 redirection, which actually was solved by a session transfer that is specific to this problem. So if you are reading this answer I can tell the way I did to preserve cookie information in the question is correct and still thank you for all those put effort and thought on this question.
Thanks
Related
I am attempting to create a login page on my mini site that allows users to download material. I am struggling with the xhr request, in order to check if the password and username are valid. Is the following code sufficient in what I am trying to do? Any help would be appreciated.
function login() {
const xhr = new XMLHttpRequest();
const uri = "localhost"; // uri for request inserted here
xhr.open("GET", uri, true, Username, Password);
xhr.withCredentials = true;
xhr.onload= function() {
const resp = JSON.parse(xhr.responseText);
document.getElementById("Login").innerHTML = resp;
}
xhr.send(null)
}
Although it is your personal wish but one should never check username and password validity using xhr. These should always be done with form submissions. And the next thing is that it is never safe to use GET in requests for fields such as passwords. Always use passwords.
You need to edit your code.
I have been googling for hours now. I've read a dozen "answers" on Stackoverflow, all of them using jQuery.
This is the common answer...
The ajax-request will follow that redirect afaik
Well, it doesn't.
I am trying to send a PUT from a form via native JS AJAX
[Please I beg you, don't tell me to use jQuery. I found a bug in jQuery via PUT
(1) so I'm going around it]
This is my code snippet...
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(data);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
This block works great, I can POST, PUT and DELETE without issues. The server receives the data and updates the DB according to the sent METHOD just fine.
My (SLIM based) PHP, upon successful completion, returns a 302 and a URL to go to.
This process works using POSTMAN hitting the PHP, and it goes to the right page.
Opening Chrome Tools/Network, it shows that the PHP is returning a 302 and than a 200
My response object contains the full HTML for a page in the responseText property.
Funny thing is, if I hard code a bad URL,the browser goes to my 404 page fine.
Your thoughts? (Please don't ask me or tell me to use jQuery)
EDIT/ADDENDUM -----------------------
I have discovered that the redirect is using the same METHOD of the original call.
I'm doing
PUT /user/1
the Redirect is doing
PUT http://myserver.test/
This is the right place to go. Now I understand the 405.
I don't have a PUT route defined, therefore the 405.
I create a PUT route and it works in POSTMAN but still gives me a 405 in Chrome and Firefox.
I have 2 issues to solve:
1) change the METHOD on the redirect
2) figure out why the browser doesn't like the 307
I found "a" solution. I'm not sure I like it, but...
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(data);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
window.location.replace(xhr.responseURL); // <---- solution
}
};
I have a Tomcat server that only serves static files(html, css, js). When the request comes in it gets intercepted by a proxy server. Proxy server authenticates the user and adds a userId field to the header and forwards it my Tomcat server.
How can I access userId that has been stored in the header from javascript?
Thank you
You can't, BUT...
If such header is send to the browser you could make an ajax request and get that value from it.
This little javascript could be useful in your case. Watch out, use it with caution and sanitize or change the URL depending on your needs, this is just a "concept", not a copy-paste solution for every case. In many other cases this is not a valid solution, cause it is not the header of the loaded document, but another request. Anyway the server, content-type, etc can be use quite safely.
xmlhttp = new XMLHttpRequest();
xmlhttp.open("HEAD", document.URL ,true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
console.log(xmlhttp.getAllResponseHeaders());
}
}
xmlhttp.send();
EDIT: Ooops, seem already anwser that part also... Accessing the web page's HTTP Headers in JavaScript
Didn't read it all.
Use below script for access userId
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
headers = req.getAllResponseHeaders().split("\n")
.map(x=>x.split(/: */,2))
.filter(x=>x[0])
.reduce((ac, x)=>{ac[x[0]] = x[1];return ac;}, {});
console.log(headers.userId);
I am trying to access WCF service hosted on server. The service is using SSL connection.
I assigned a self signed certificate in IIS.
The service is a restfull service.
I tried with two different scenarios:
1st scenario :
I hosted the web site to same server(client application which access service)
In this case the service is accessible and able to get response from service.
2nd scenario :
I hosted the web site to localhost,local machine.
From here when I am trying to make request to service method which is hosted on different web server it is not accessible.
Showing error "Method not allowed"
Here is code :
function testHttps()
{
jsonText3=JSON.stringify({"Name":"Avinash"});
url="https://ServerIP/WcfSecureService/Service.svc/GetName";
var xhr = createCORSRequest('POST', url);
if (!xhr) {
alert('CORS not supported');
}
xhr.onload = function() {
alert(xhr.responseText);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.setRequestHeader('Content-Type', 'application/json') ;
xhr.send(jsonText3);
}
function createCORSRequest(method, url)
{
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr)
{
xhr.open(method, url, true);
}
else if (typeof XDomainRequest != "undefined")
{
xhr = new XDomainRequest();
xhr.open(method, url);
} else
{
xhr = null;
}
return xhr;
}
How to make CORS call success with HTTPS?
I do not want to install any certificate on client site.
How to authenticate service from Javascript?
Please suggest...
Thanks for your help in advance.
--Avinash
Check this and this out.
I think your problem is not about https: is the server responding with an header like the following?
Access-Control-Allow-Origin: *
In case it's not, it's probably filtering out your local referer.
Furthermore, if you're using credentials the server can't use the "*" wildcard and has to specify every allowed domains, which don't include localhost, I guess.
i try to make a Firefox Addon which runs a XMLHttp Request in Javascript. I want to get the data from this request and send it to *.body.innerhtml.
That's my code so far...
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://xx.xxxxx.com", true);
xhr.send();
setTimeout(function() { set_body(xhr.responseHtml); }, 6000);
Instead of receiving the data, I get "undefined". If I change xhr.responseHtml to responseText I get nothing. I don't know why I'm getting nothing. I'm working on Ubuntu 12.04 LTS with Firefox 12.0.
If you need any more details on the script please ask!
Update:
set_body Function
document.body.innerHTML = '';
document.body.innerHTML = body;
document.close();
Update SOLVED:
I had to determine the RequestHeaders (right after xhr.open):
xhr.setRequestHeader("Host", "xxx");
For following Items: Host, Origin and Referer. So it seems there was really a problem with the same origin policy.
But now it works! Thanks to all!
when you set the last param of open to true you are asking for an async event. So you need to add a callback to xhr like so:
xhr.onReadyStateChange = function(){
// define what you want to happen when server returns
}
that is invoked when the server responds. To test this without async set the third param to false. Then send() will block and wait there until the response comes back. Setting an arbitrary timeout of 6 seconds is not the right way to handle this.
This code should work:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
set_body(xhr.responseText);
}
};
xhr.open("GET", "http://xx.xxxxx.com", true);
xhr.send();
Make sure that you are getting a correct response from URL http://xx.xxxxx.com. You may have a problem with cross-domain calls. If you have a page at domain http://first.com and you try to do XMLHttpRequest from domain http://second.com, Firefox will fail silently (there will be no error message, no response, nothing). This is a security measure to prevent XSS (Cross-site scripting).
Anyway, if you do XMLHttpRequest from a chrome:// protocol, it is considered secure and it will work. So make sure you use this code and make the requests from your addon, not from your localhost or something like that.