XHR Failed Loading Post because of withCredentials - javascript

I have a problem with my script where I got an error message such as this
XMLHttpRequest cannot load https://igoblogging.com/likebutton/. The
value of the 'Access-Control-Allow-Origin' header in the response must
not be the wildcard '*' when the request's credentials mode is
'include'. Origin 'http://nielinfo.com' is therefore not allowed
access. The credentials mode of requests initiated by the
XMLHttpRequest is controlled by the withCredentials attribute.
I tried to load a cookie from cross domain. Here is my javascript code
var xhr = new XMLHttpRequest();
xhr.open('POST', linkbased+'/likebutton/',true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.withCredentials = true;
xhr.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200) {
if(document.getElementById("igblikebutton")){
document.getElementById("igblikebutton").innerHTML = this.responseText;
}
}
}
xhr.send(data);
And here is my php script
header('Access-Control-Allow-Origin: http://nielinfo.com');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
header('Access-Control-Allow-Credentials: true');
echo $_COOKIE['username'];
Here is the response headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Methods:POST
Access-Control-Allow-Origin:*
Cache-Control:max-age=604800
Content-Type:text/html; charset=utf-8
Date:Wed, 05 Jul 2017 07:09:04 GMT
Expires:Wed, 12 Jul 2017 07:09:04 GMT
Server:Apache/2.4.25 (CentOS)
Strict-Transport-Security:max-age=2592000; preload
Transfer-Encoding:chunked
Upgrade:h2
X-Content-Type-Options:nosniff
X-Frame-Options:SAMEORIGIN
X-Powered-By:PHP/5.4.45
X-Supported-By:Kloxo-MR 7.0
X-XSS-Protection:1;mode=block
And here is the request headers
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:82
Content-type:application/x-www-form-urlencoded
Cookie:__cfduid=d239fe9b5de5b706676a60c112ccbd5d01497599052; _ga=GA1.2.91093954.1497599466; kloxo-clientname=admin; kloxo-classname=client; kloxo-session-id=L5b4xFTJphHH9kQN1AidVz6jpQw2QuazpkJd4TmW4E71fXMOPb; __atuvc=1%7C25; HstCfa3839354=1498146551883; HstCla3839354=1498146551883; HstCmu3839354=1498146551883; HstPn3839354=1; HstPt3839354=1; HstCnv3839354=1; HstCns3839354=1; username=flameblue59; ip=118.136.215.7; PHPSESSID=9614c4fcf759c74577837fdd5dad1c3f
Host:igoblogging.com
Origin:http://nielinfo.com
Referer:http://nielinfo.com/who-is-dullahan-the-headless-rider-who-will-terrified-you/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
The weird thing, when I remove xhr.withCredentials. Its working fine but the cookie won't load. I think the problem because of withCredentials usage. I really appreciate any solution here. Thank you so much.

Related

Failed to load JSON file using JQuery [duplicate]

The AJAX request works fine, but the moment I add a header via beforeSend or headers, an OPTIONS pre-flight request is made and the GET request is aborted.
Code: $.ajax({
type: "GET",
crossDomain: true,
beforeSend: function (xhr)
{
xhr.setRequestHeader("session", $auth);
},
url: $url,
success: function (data) {
$('#something').html(data);
},
error: function (request, error) {
$('#something').html("<p>Error getting values</p>");
}
});
Similar AJAX Request w/o headers specified (the moment I add/modify header, an OPTIONS call is made)
Request GET /api/something?filter=1 HTTP/1.1
Referer http://app.xyz.dj/dashboard
Accept application/json, text/javascript, */*; q=0.01
Accept-Language en-US
Origin http://app.xyz.dj
Accept-Encoding gzip, deflate
User-Agent Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; MASMJS; rv:11.0) like Gecko
Host 162.243.13.172:8080
DNT 1
Connection Keep-Alive
Cache-Control no-cache
Similar Server Response Header (for GET request)
Response HTTP/1.1 200 OK
Server Apache-Coyote/1.1
Access-Control-Allow-Origin *
Access-Control-Allow-Methods GET, POST, DELETE, PUT, OPTIONS, HEAD
Access-Control-Allow-Headers Content-Type, Accept, X-Requested-With
Access-Control-Allow-Credentials true
Content-Type application/json
Transfer-Encoding chunked
Date Thu, 09 Jan 2014 14:43:07 GMT
What I am doing wrong?
Solved.
Thanks #JasonP for pointers. Changed Server Response Headers from
Access-Control-Allow-Headers:*
to specific ones
Access-Control-Allow-Headers: Content-Type, Accept, X-Requested-With, Session
and now it works!

How does cross-origin AJAX request 'withCredentials' figure out which cookies to use?

I can't figure out how this AJAX request knows which cookie to use. It uses the right one, but how does it know which one is the right one, or where is it specified (implicitly)?
$.ajax({
url: 'https://remote-host.de/api/v2/session',
crossDomain: true,
xhrFields: {
withCredentials: true
},
statusCode: {
401: function() {
// do stuff
},
200: function() {
// do stuff
}
}
});
The request looks like this when I inspect it with Chrome and it has the right cookie set (the one of the remote host I am trying to request the login state from):
Accept:*\/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Cookie:_foo-bar_session=WjRMdExSQ1F6UlczbER0Ui9sQU9NNllIRWo1NmpCSXo2REh6akZmM1czODZ0M29adGh4aWg3ZmdrYWdxSU5KRVptUi8ybDladmJMHJhZWKZ3A5NlJCOTdWeFpCRGJQdHVvMnlxb0VQeWlCMGRtNDkxNDF3QVdhcnVRenlsQXExa3RNEtwZ1RNMW9oaE5TV1hLbHdnPT0tLXhtYUo3YytHY2wxWTFxanlXVTJjdlE9PQ%3D%3D--b22797a9b004d0759a43f4d94686edf909610a06
Host:remote-host.de
Origin:http://localhost:3001
Referer:http://localhost:3001/de
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
The response:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Methods:GET, POST, PATCH, PUT, DELETE, OPTIONS, HEAD
Access-Control-Allow-Origin:http://localhost:3001
Access-Control-Expose-Headers:ETag
Access-Control-Max-Age:86400
Cache-Control:no-cache
Connection:keep-alive
Content-Type:application/json; charset=utf-8
Date:Wed, 22 Mar 2017 10:18:15 GMT
Server:nginx
Set-Cookie:_foo-bar_session=SGhyWGtWTFVoc1AzUWlldmIxTjFGVXVCQU9YVkduSDFISWtLamwwT01heW5HN25saVNyYWJ1b2ZDZDI4RzNGT1BzYWZOOHNVK21DN0kxNmJRS1VDSTdwb1VVS2NtcTZ3Y1dRYUJSaTYxckpOdDZFZ2RpRlQzTHZPdDdTTjljenZzQ1hTUjlCN0RoZUlkcWlpNm5KK2VRPT0tLTkwUlNuM0Z6TDZ2TWJjZVVSUExpb0E9PQ%3D%3D--568e4688b6ff5e17faa32a3bab1a7cf01807a581; path=/; HttpOnly
Transfer-Encoding:chunked
X-Content-Type-Options:nosniff
X-Frame-Options:SAMEORIGIN
X-Request-Id:b43ce1c4-2c80-4sd5-8333-0g93ae4df940f
X-Runtime:0.013627
X-XSS-Protection:1; mode=block
But how does it know?
Unless I’m misunderstanding the question, the browser just sends back whatever cookies it has that match the domain the request is being made to, and that match any path in the cookie.
How cookies work? has more details, with links to articles explaining how browsers handle cookies.

Allowing cross domain ajax requests with Meteor

Server side setup
JsonRoutes.setResponseHeaders({
"Cache-Control": "no-store",
"Pragma": "no-cache",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, PUT, POST, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With"
});
Client side setup
var getRecentPosts = function (token) {
$.ajax({
url: "http://localhost:3000/publications/recentPostsAndComments",
method: "GET",
headers: {
"Authorization": "Bearer " + token,
"Content-Type": "application/json"
},
// contentType: "application/json",
success: function (data, status, xhr) {
debugger
},
error: function (xhr, status, err) {
debugger
}
});
}
I always get caught inside the error callback because of the following error:
XMLHttpRequest cannot load http://localhost:3000/publications/recentPostsAndComments. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:5000' is therefore not allowed
access.
Is there anything noticeable that I am missing here?
Update:
in the network tab, I see one option request that succeeds, but I don't see a GET request that's supposed to be sent.
Remote Address:127.0.0.1:3000
Request URL:http://localhost:3000/publications/recentPostsAndComments
Request Method:OPTIONS
Status Code:200 OK
Response Headers
view source
connection:keep-alive
content-type:text/html; charset=utf-8
date:Sat, 19 Sep 2015 23:53:48 GMT
transfer-encoding:chunked
vary:Accept-Encoding
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,ko;q=0.6
Access-Control-Request-Headers:accept, authorization, content-type, x-requested-with
Access-Control-Request-Method:GET
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:3000
Origin:http://localhost:5000
Pragma:no-cache
Referer:http://localhost:5000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36
This is what I sometimes use and it works great.
//Server Side PHP
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 2000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X- Requested-With');
?>
As you know, it should be placed before any code....

Error using CORS with JavaScript

I have been reading the questions on the stackoverflow regard CORS implementation for a couple weeks but I'm still stuck on a couple errors. Any pointers in the right direction would be great. Thanks in advance.
Here's what I have:
SERVER SETUP
public void doOptions(HttpServletRequest request, HttpServletResponse response)
throws IOException {
//The following are CORS headers. Max age informs the
//browser to keep the results of this call for 1 day.
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, POST");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
response.setHeader("Access-Control-Max-Age", "86400");
//Tell the browser what requests we allow.
response.setHeader("Allow", "GET, HEAD, POST, TRACE, OPTIONS");
CLIENTSIDE Javascript
OLVM Test Page
<SCRIPT language="JavaScript">
function setMessage(){
msg = "";
var xmlHttp;
msg = msg + "110###B#~20#OLVM-GL-ACCOUNT#~20";
xmlHttp=new XMLHttpRequest();
xmlHttp.open("POST","http://MYSITE.ceco.com:2900/OLVM/OLVMGateway",false);
xmlHttp.setRequestHeader("Content-Type","text/xml");
xmlHttp.send(msg);
alert(xmlHttp.responseText);
return;
}
</SCRIPT>
</head>
<body bgcolor="#FFFFFF">
<p> </p>
<p align="left"><font face="Arial" size="6"><b>OLVM - PBF </b></font></p>
<input type="button" name="submit" value="Submit To Server" onClick= "setMessage()" >
</body>
</html>
OPTIONS HEADER info I see when debugging
Request URL:http://MYSITE.ceco.com:2900/OLVM/OLVMGateway
Request Method:OPTIONS
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:MYSITE.ceco.com:2900
Origin:null
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36
Response Headersview source
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:GET, POST
Access-Control-Allow-Origin:*
Access-Control-Max-Age:86400
Allow:GET, HEAD, POST, TRACE, OPTIONS
Content-Length:0
Date:Wed, 02 Jul 2014 12:13:41 GMT
POST HEADER info I see when debugging
Request URL:http://MYSITE.ceco.com:2900/OLVM/OLVMGateway
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:337
Content-Type:text/xml
Host:MYSITE.ceco.com:2900
Origin:null
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36
Request Payload
110###B#~20#OLVM-GL-ACCOUNT#~20
Response Headersview source
Content-Length:7
Content-Type:text/html
Date:Wed, 02 Jul 2014 12:13:41 GMT
ERROR I get
XMLHttpRequest cannot load http://MYSITE.ceco.com:2900/OLVM/OLVMGateway. No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access. OLVM_V5.html:59
Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://MYSITE.ceco.com:2900/OLVM/OLVMGateway'.
You are only adding the headers to the OPTIONS response.
However, for the request to succeed you have to set those headers both on OPTIONS and on POST responses.
Also note that your code will not work in IE8 as it requires proprietary XDomainRequest object as you can see in HTML5Rocks.com example:
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
var xhr = createCORSRequest('GET', url);
if (!xhr) {
throw new Error('CORS not supported');
}

Get request failed with custom header

Here is my AngularJS code, (it works fine if I remove the header option).
$http.get(env.apiURL()+'/banks', {
headers: {
'Authorization': 'Bearer '+localStorageService.get('access_token')
}
})
Here is the request:
OPTIONS /banks HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:8081
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36
Access-Control-Request-Headers: accept, authorization
Accept: */*
Referer: http://localhost:8081/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,vi;q=0.6
And response:
HTTP/1.1 404 Not Found
Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE
Access-Control-Allow-Origin: http://localhost:8081
Content-Type: text/plain; charset=utf-8
Date: Mon, 17 Mar 2014 11:05:20 GMT
Content-Length: 19
I added both Accept and Authorization header but the request still fails?
Does the capitalization (I mean authorization vs Authorization) result in that failure? If yes, how can I make AngularJS stop doing that?
if origin := req.Header.Get("Origin"); origin == "http://localhost:8081" {
rw.Header().Set("Access-Control-Allow-Origin", origin)
rw.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
rw.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
Go server routing code:
r := mux.NewRouter()
r.HandleFunc("/banks", RetrieveAllBank).Methods("GET")
http.ListenAndServe(":8080", r)
OK, the issue because I fotgot to handle the "OPTIONS" request (to make a CORS browser will send a preflight OPTIONS request first and then the 'real' request if accepted by the server).
I only need to modify my Go server (see the comment):
func main() {
r := mux.NewRouter()
r.HandleFunc("/banks", RetrieveAllBank).Methods("GET")
http.ListenAndServe(":8080", &MyServer{r})
}
type MyServer struct {
r *mux.Router
}
func (s *IMoneyServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if origin := req.Header.Get("Origin"); origin == "http://localhost:8081" {
rw.Header().Set("Access-Control-Allow-Origin", origin)
rw.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
rw.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
// Stop here if its Preflighted OPTIONS request
if req.Method == "OPTIONS" {
return
}
// Lets Gorilla work
s.r.ServeHTTP(rw, req)
}

Categories