Here is the problem,
I try to get an authentication token from my alfresco community server with a js (angular 4) script. The request seems to be blocked by "CORS header missing"...
The login/password are ok since I can try the login URL directly in my browser and I get the expected result (xml) like this :
https://www.my-url.com/alfresco/service/api/login?u=username&pw=password
I get this as a result :
Now, I come to my web app and I need to retrieve this ticket from an http call, like this (with angular 4 service) :
getTicket(user: User): Observable<boolean>{
let headers = new Headers();
headers.append('Access-Control-Allow-Origin','*');
return this.http.post('https://www.my-url.com/alfresco/service/api/login',{'u':'username','pw':'password'},{headers:headers}).map(response => {
console.log('response : '+JSON.stringify(response));
});
}
I hardcoded the u/pw variables, I also tried to name them "user" & "password", and I tried GET method too, but nothing changes, the only thing I get back is a Cors problem. Result in console :
OPTIONS XHR https://www.my-url.com/alfresco/service/api/login
[HTTP/1.1 200 OK 39 ms]
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource ... Reason: CORS header
'Access-Control-Allow-Origin' missing.
Request data :
Response Headers :
Allow: "OPTIONS, GET, POST"
Content-Length: "0"
Date : "Wed, 11 Oct 2017 14:37:45 GMT"
Server: "Apache-Coyote/1.1"
Request Headers :
Host : "www.my-url.com"
User-Agent : "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0"
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
Accept-Language : "en-US,en;q=0.5"
Accept-Encoding: "gzip, deflate"
Access-Control-Request-Method: "POST"
Access-Control-Request-Headers: "access-control-allow-origin"
Origin: "http://localhost"
Connection: "keep-alive"
I also tried removing the headers I manually create for the request, but no effect...
How To Enable CORS in alfresco V5.2 ? Put enablecors-1.0.jar
in modules/platform folder.
Related
The Frontend JavaScript sends a CORS fetch POST with login credentials to the backend. However the Set-Cookie (for authentication) in the response from the backend is not stored in the browser, why is that the case?
The Set-Cookie is shown in the fetch response and gets recognized as a http Cookie from the browser, however it doesn't get saved.
I've been through a lot of entries on this issue and checked things like "credentials: 'include'", the correct Response Headers and SameSite properties of the cookie.
Would really appreciate someone's expert opinion, since I couldn't resolve the issue for days now. ;)
This is the webpage for login:
https://www.evs-media.com/tests/t5
For the backend I'm using a Rest API No-Code Tool: https://www.xano.com
Domain Frontend: https://www.evs-media.com
Domain Backend API: https://x8ki-letl-twmt.n7.xano.io/api:s900chrT
On the backend server-side this is what the Request Header looks like:
"Sec-Fetch-Site: cross-site",
"Sec-Fetch-Mode: cors"
"Sec-Fetch-Dest: empty"
"Dnt: 1","Origin: https://www.evs-media.com"
"Content-Type: multipart/form-databoundary=---------------------------32748419764181237672921298736"
"Referer: https://www.evs-media.com/"
"Accept-Encoding: gzip, deflate, br"
"Accept-Language: en-US,en;q=0.5"
"Accept: */*","User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:102.0) Gecko/20100101 Firefox/102.0"
"Content-Length: 295"
"X-Scheme: https"
"X-Forwarded-Scheme: https"
"X-Forwarded-Proto: https"
"X-Forwarded-Port: 443"
"X-Forwarded-Host: x8ki-letl-twmt.n7.xano.io"
"X-Forwarded-For: 79.242.71.235"
"X-Real-Ip: 79.242.71.235"
"X-Request-Id: c459f42dad416f9b5d0d53df307632e9"
"Host: x8ki-letl-twmt.n7.xano.io"
This is the Response Header on the backend server-side:
"Accept-Ranges: none"
"X-XSS-Protection: 1; mode=block"
"X-Frame-Options: deny"
"Access-Control-Allow-Methods: GET, POST, DELETE, PUT, PATCH, OPTIONS, HEAD"
"Access-Control-Allow-Headers: Cache-Control, Content-Type, Content-Length, Authorization, Accept, Accept-Encoding, User-Agent, X-Requested-With, X-APP-KEY, X-Data-Source, X-Branch"
"Access-Control-Allow-Credentials: true"
"Access-Control-Max-Age: 86400"
"X-App: hit"
"set-cookie: myfirstcookie= Bearer eyJhbGciOiJBMjU2S1ciLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwiemlwIjoiREVGIn0.jowMcpyEUJZPSxDuIWbGRT2IMabWHfYkBX9tr0_t0agn8wkAKFlc5tUPGpAdKf-9Rhgo8IE5oCwKTNJ0hL1VqZv2D4Vl2XJC.614vZOklc-w9tlAcpxf8Sw.d1OGC6ownAZid1q0XwbGOVP_AKTCMuPG9ehcCbG2iklLHzAeela9r_78t5IN30FwcgHkxNPlh0opQuw5t1DXqjosVTWwgdFzOhv_Add4vznjo_Gd6bv-tnFOLeQVlcfLb3CNzGvHcC8rII9rEy_HjcNx9Xv9DqXIM7i2KPYf33Q.mLjsCPzAUINdZLPydsJyaHNI8v6AISAU8mvz0pRrLw4; Expires=Wed 20 Jul 2022 07:28:00 GMT; Max-Age=2592000; Domain=.x8ki-letl-twmt.n7.xano.io/api:s900chrT; path=/; SameSite=None; Secure; HttpOnly;"
"Access-Control-Allow-Origin: https://www.evs-media.com"
"Access-Control-Expose-Headers: Set-Cookie"
"Content-Type: application/json; charset=UTF-8"
This is what the Request Headers look like on the frontend client-side:
Screeenshot of Request Headers
This is the fetch JavaScript on the frontend:
const myForm = document.getElementById('myForm');
myForm.addEventListener('submit', function (e) {
e.preventDefault();
const formData = new FormData(this);
fetch('https://x8ki-letl-twmt.n7.xano.io/api:s900chrT/auth/logintest', {
method: 'POST',
credentials: 'include' ,
body: formData
}).then(function (response) {
return response.text();
}).then(function (text) {
console.log(text);
}).catch(function (error) {
console.error(error);
})
})
SO my graphql api is at https://gpbaculio-tributeapp.herokuapp.com/graphql I configured the uploaded, headers like this:
const fetchQuery = (operation, variables) => {
return fetch('/graphql', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
query: operation.text,
variables,
}),
}).then(response => {
return response.json()
})
}
I have read from MDN.
For requests without credentials, the server may specify "*" as a
wildcard, thereby allowing any origin to access the resource.
So I am trying to publish the app in codepen, and this is my error:
Failed to load https://gpbaculio-tributeapp.herokuapp.com/graphql:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'https://s.codepen.io'
Why is it telling me it doesn't pass 'Access-Control-Allow-Origin' headers?
Is there something wrong with my headers config?
You are setting the header in your request (in the client). The Access-Control-Allow-Origin header needs to be set on the server-side, and when you make a request, the response should contain that header.
The reason behind this header is that not every webpage can query every third-party domain. Being able to set this header from the request would defeat that whole point.
Try setting cors options and Access-Control-Allow-Origin headers in server side.
const graphQLServer = express();
const corsOptions = {
origin(origin, callback) {
callback(null, true);
},
credentials: true
};
graphQLServer.use(cors(corsOptions));
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
graphQLServer.use(allowCrossDomain);
This may help you
CORS specification states, that requests for resources are "preflighted" with HTTP OPTIONS request, and reply headers for that OPTIONS must contain header:
Access-Control-Allow-Origin: *
you might check it with curl:
$ curl -I -X OPTIONS https://gpbaculio-tributeapp.herokuapp.com/graphql
HTTP/1.1 405 Method Not Allowed
Server: Cowboy
Connection: keep-alive
X-Powered-By: Express
Allow: GET, POST
Content-Type: application/json; charset=utf-8
Content-Length: 97
Date: Sat, 23 Sep 2017 11:24:39 GMT
Via: 1.1 vegur
Add OPTION handler with needed header, so your server answers:
$ curl -I -X OPTIONS https://example.localhost/
HTTP/1.1 204 No Content
Server: nginx/1.4.7
Date: Sat, 23 Sep 2017 11:27:51 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range
Content-Type: text/plain; charset=utf-8
Content-Length: 0
The problem is the browser's cross-origin problem.
The Access-Control-Allow-Origin header should be return by the server's response, and the header means the origin domain that can access to the API.
The client's request often take a header Origin, it's value is the current host address, like, www.example.com.
The values of Access-Control-Allow-Origin must contain the value of Origin means that the origin can access this API service. And then the browser will continue the request. If not, the browser will cancel the request.
More infomation, refre to CORS https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
I am trying to make a http get request from AngularJS. It is only working in the Internet Explorer 11. When I try to make a POST Call in Chrome, Firefox or Edge it is not working.
I get the following error:
CORS Error in Chrome
This is my AngularJS Call:
$http({
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
url: URL
}).then(function successCallback(response) {
console.log(response.data);
}, function errorCallback(response) {
console.log(response.status);
console.log(response.headers);
console.log(response.config);
});
As backend I have a Java Spring MVC Application and I have set the following headers:
HttpHeaders responseHeader = new HttpHeaders();
responseHeader.set("Access-Control-Allow-Origin","*");
responseHeader.set("Access-Control-Allow-Headers:","Content-Type");
responseHeader.set("Access-Control-Allow-Methods","POST, GET, PUT, OPTIONS, DELETE");
responseHeader.set("Content-Type","application/json");
But I saw that angular never reaches the backend when I set a breakpoint! This is very confusing, I already searched a lot in the internet and tried to changed the default AngularJS Content-Type header:
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
I tried also to change the Content-Type in the POST-Request to "application/x-www-form-urlencoded" - with no effect.
Note: The backend and the frontend runs on the same dev machine. The only difference is the port, that's why I am confused that I get a CORS Error at all...
I have this problem only with POST-Requests; GET works like a Charm
Edit 1:
I thought that this is a Problem with cors and that i use different ports, but is it possible that I can turn that off?
Edit 2:
Now i try to get it to work with a local tomcat. Now i see in the Tomcat the request will reach the server:
<< Client IP>> - - [28/Jun/2017:13:43:24 +0200] "OPTIONS <<URL>> HTTP/1.1" 403 -
The Response is now HTTP 403. In Browsers network tab i can see the following request header:
Host: <<backend ip>>:8080
User-Agent: <<user agent>>
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: de,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: access-control-allow-origin,content-type
Origin: http://<<Ip of host>>
Connection: keep-alive
The Response of that request header is the following:
Content-Type: text/plain
Content-Length: 0
Date: Wed, 28 Jun 2017 11:43:24 GMT
I have set the cors filter like the example in the tomcat documentation: http://tomcat.apache.org/tomcat-7.0-doc/config/filter.html#CORS_Filter
When i make a get request, it is still working and all CORS headers are present.
I think there is something wrong with the first OPTIONS request. I dont know why the tomcat do not set the CORS header when the OPTIONS request comes.
In your Spring Controller, add #CrossOrigin('http://localhost:8080')
annotation. Of course, substitute out the port of your angular application.
Since you are getting 400 (not authorized) error, the request is not reaching the service itself. Most probably the request domain is blocked, you may see if XHR requests are allowed and check cross origin policy if needed.
I figured it out. I made a completly new angularjs testwebsite. This is my working angularjs Code:
var req = {
method: 'POST',
url: 'myURL',
headers: {
'Content-Type': undefined
},
data: "JSON BODY DATA"
}
$http(req).then(function successCallback(response) {
console.log(response.data);
}, function errorCallback(response) {
console.log(response.data);
});
}]);
I deleted anything that changed the default angularjs headers.
The headers of my Spring MVC Application are the following:
HttpHeaders responseHeader = new HttpHeaders();
responseHeader.set("Access-Control-Allow-Origin","http://<<clientip>>");
responseHeader.set("Access-Control-Allow-Headers:","Content-Type");
responseHeader.set("Access-Control-Allow-Methods","POST, GET, PUT, OPTIONS, DELETE");
responseHeader.set("Content-Type","application/json");
I dont know the exactly cause why it is working now. Maybe it was because i modified the default headers in AngularJS.
After searching for a while, I cannot find the answer yet.
My problem is when I call a web service function setRequestHeader, I got the error "not allowed by Access-Control-Allow-Origin".
Here is my javaScript code:
var loginController = new sap.ltst.login.loginController({controllerName: "sap.ltst.login.loginController"});
var session = loginController.login("I051486", "123456789");
var config = {};
$.ajax({
beforeSend: function(req) {
req.setRequestHeader('Authentication', 'Authentication-Token ' + session.session_token);
},
url : "http://localhost:8081/com.sap.st.gtpapi/program/"
+ this.program + "/configs",
dataType : 'json',
type : 'GET',
async : false,
success : function(data) {
config = data;
}
});
return config;
In web service side, I have a function that I can enable or disable the authentication. I tried to set the auth as false (not check the auth) then remove setRequestHeader, I got no error and the web service returns me some data.
In another way I tried to put it back, I got the error.
XMLHttpRequest cannot load http://localhost:8081/gtpapi/program/Business%20Intelligence%20platform%204.1%20(BI%20Aurora%204.1)/configs. Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin.
So I don't think that it's the problem of the auth because in the web service side, I disable the auth verification.
Let's move to the web service side, this is the interface:
public static final String HEADER_AUTH_TOKEN = "Authentication-Token";
#GET
#Consumes({MediaType.APPLICATION_JSON})
#Produces({MediaType.APPLICATION_JSON})
#Path("/guid_{planId}/packages/{packId}/{results}")
public Response setPackageResult(#PathParam("planId") final String planGuid, #PathParam("packId") final String packGuid, #PathParam("results") final String results, #HeaderParam(WebServiceBase.HEADER_AUTH_TOKEN) String token);
This is the header response et request on Chrome:
Request URL:http://localhost:8081/com.sap.st.gtpapi/program/SBOP%20EXPLORER%204.1/configs
Request Method:OPTIONS
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Charset:UTF-8,*;q=0.5
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,fr;q=0.6
Access-Control-Request-Headers:accept, authentication, origin
Access-Control-Request-Method:GET
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:8081
Origin:http://localhost:8080
Pragma:no-cache
Referer:http://localhost:8080/LTST_Frontend/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
Response Headersview source
Allow:GET,OPTIONS,HEAD
Content-Length:0
Content-Type:text/xml
Date:Fri, 02 Aug 2013 15:44:10 GMT
Server:Apache-Coyote/1.1
I'm not sure I did some mistake whether the problem comes from javaScript or web service. Any ideas?
Put any header you want to send in the safe list:
header("Access-Control-Allow-Headers: Authentication, X-Custom-Header, .. etc");
This should be part of the CORS headers on the receiving domain.
this is driving me nutters.
jQuery 1.4.2, windows XP sp3
Here is my test.
Load firefox 3.5+
http://plungjan.name/test/testcors.html
works
Save the file to harddisk and run from there
From my office the external works and the internal does not
What is also interesting is that I cannot run both in one go.
Background:
I do a GET to an internal web service that uses CORS.
Please do NOT post any answers about FF not handling cross domain request when it does since v3.5 as detailed here and here
It works in IE8 and FF3.6.6 from one server to the other and now almost from file system (file:///) to service.
Only from file system and only when FF 3.6.6 needs to negotiate (the user is already logged in, authorised and sends the credentials!) do I not get the data after negotiation. jQuery xhr returns status 0 and no data/responseText or whatever
Seems to me, jQuery reacts and saves the xhr from the 401 rather than from the 200 OK later
Here is the result I get at the end of the communication when I alert the XHR object:
Status:success
Data:[]
XHR:
some native functions,
readyState:4
status:0
responseXML:null
responseText:
withCredentials:true
if I make a call to the same server but without needing credentials, the data is returned just fine cross domain
So the communication is as follows:
GET /restapplicationusingcors/authenticationneeded-internal/someid
Accept: application/json
Accept-Language: en
.
.
Origin: null
Cookie: LtpaToken=...
the return is
HTTP/1.1 401 Unauthorized
Server: Apache
Pragma: No-cache
Cache-Control: no-cache
Expires: Thu, 01 Jan 1970 01:00:00 CET
WWW-Authenticate: Negotiate
Connection: close
Transfer-Encoding: chunked
Content-Type: text/html
Then FF sends
GET /restapplicationusingcors/authenticationneeded-internal/someid HTTP/1.1
Host: myhost.myintranet.bla
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6
Accept: application/json
Accept-Language: en
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Origin: null
Cookie: LtpaToken=....
Authorization: Negotiate ....
and is rewarded with the file I need, but cannot get at in FF:
HTTP/1.1 200 OK
Date: Tue, 20 Jul 2010 12:08:39 GMT
Pragma: No-cache
Cache-Control: no-cache, max-age=600, s-maxage=3600
Expires: Thu, 01 Jan 1970 01:00:00 CET
X-Powered-By: ...
Content-Disposition: inline;filename=nnnnnn.json
Content-Language: en
Access-Control-Allow-Origin: ...
Keep-Alive: timeout=6, max=70
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/json;charset=UTF-8
THE DATA SENT FROM THE SERVER IS NOT IN THE XHR OBJECT
Here is my code
function getJSON(url,func,lang) {
accept = 'application/json';
lang=lang?lang:"*";
// gruesome hack to handle that APPENDS the mime header to */* !!!
// NOW HANDLED by first setting Accept to "" !!!
// if ($.browser.msie && url.indexOf('serveAsMime')==-1) {
// url+= '?serveAsMime='+accept;
// }
if (currentRequest != null) currentRequest.abort();
var requestObjectJSON = {
url : url,
// dataType: "json",
method : 'get',
beforeSend: function(xhr){
xhr.setRequestHeader('Accept', ""); // IE hack
xhr.setRequestHeader('Accept', accept);
xhr.setRequestHeader('Accept-Language', lang);
if (url.indexOf('-internal') !=-1) {
try {
xhr.withCredentials = true;
alert('set credentials')
}
catch(e) {
alert('cannot set xhr with credentials')
}
}
},
success: function(data,status,xhr) {
var responseText = xhr.responseText;
var responseJSON = xhr.responseJSON;
var t = "";
try{
for (var o in xhr) t += '\n'+o+':'+xhr[o];
}
catch(e) {
if (e.message.indexOf('.channel')==-1)alert(e.message);
}
alert('Status:'+status+'\nData:['+data+']\nXHR:'+t);
func(responseText);
},
}
currentRequest = $.ajax(requestObjectJSON);
}
This is a stab in the dark since I don't fully understand your problem, but I think you might be having a problem with file: URLs, which are not treated as having any origin. I'm not sure it's even possible to authorize CORS from a file URL.
So you need to set an ajax prefilter in your model/collection in order to use CORS. Otherwise it doesn't send the cookie.
$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
options.xhrFields = {
withCredentials: true
};
});
I put this in my Model/Collection initialize function.
These are the conditions to be met to make CORS working with secured services:
Service response should contain header Access-Control-Allow-Credentials: true (see Requests with credentials and Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true).
Service response header Access-Control-Allow-Origin should not be *. The idea is to return the value passed by client in header Origin (see examples in this post).
According to specification, OPTIONS method should return HTTP code 200, thus it cannot be secured (see The CORS).
For methods PUT/POST that need to pass certain request headers to service (like Content-Type or Accept), these headers need to be listed in Access-Control-Allow-Headers (see jQuery AJAX fails to work when headers are specified)
JavaScript should set this XMLHttpRequest property: xhr.withCredentials = true; (as answered by Kirby)
Altogether configuration for Apache:
# Static content:
SetEnvIf Request_URI ".*" no-jk
# RESTful service:
SetEnvIf Request_URI "^/backend/" !no-jk
SetEnvIf Request_Method "OPTIONS" no-jk
# Fallback value:
SetEnv http_origin "*"
SetEnvIf Origin "^https?://(localhost|.*\.myconpany\.org)(:[0-9]+)?$" http_origin=$0
Header set Access-Control-Allow-Credentials "true"
Header set Access-Control-Allow-Origin "%{http_origin}e"
Header set Access-Control-Allow-Methods "GET,POST,PUT,DELETE"
Header set Access-Control-Allow-Headers "Content-Type, Accept"
JkMount /* loadbalancer
CORS with file://
If you have problems by allowing origins from the file:// protocol, according to The Web Origin Concept it should be done the same way as any other origins. I could not find information about the browser support, but I think every browser which is supporting CORS does support this one either.
The Web Origin Concept tells us the following about the file URI scheme:
4. If uri-scheme is "file", the implementation MAY return an
implementation-defined value.
NOTE: Historically, user agents have granted content from the
file scheme a tremendous amount of privilege. However,
granting all local files such wide privileges can lead to
privilege escalation attacks. Some user agents have had
success granting local files directory-based privileges, but
this approach has not been widely adopted. Other user agents
use globally unique identifiers for each file URI, which is
the most secure option.
According to wikipedia the domain by the file URI scheme is localhost. It is omittable by the address bar, but I don't think it is omittable in the allow origin headers. So if your browser implementation allows origin with a file URI scheme, then you should add file://localhost to your allowed origins, and everything should work properly after that.
This was how it should work, now meet reality:
I tested with current firefox 29.0.1, and it did not work. However the file:// protocol is transformed into null origin by this implementation. So by firefox the null works. I tried with a wider domain list, but I did not manage to allow multiple domains. It seems like firefox does not support a list with multiple domains currently.
I tested with chrome 35.0.1916, it works the same way as firefox did.
I tested with msie 11.0.9600. By request from the file protocol it always shows an allow blocked content button, even by not allowing the null origin. By other domains it works the same way as the previous browsers.
HTTP basic auth:
The credentials part I tried out with PHP and HTTP basic auth.
http://test.loc
Displays :-) when logged in and :-( when unauthorized.
<?php
function authorized()
{
if (empty($_SERVER['PHP_AUTH_USER']) || empty($_SERVER['PHP_AUTH_PW']))
return false;
return ($_SERVER['PHP_AUTH_USER'] == 'username' && $_SERVER['PHP_AUTH_PW'] == 'password');
}
function unauthorized()
{
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Restricted Area"');
echo ':-(';
}
if (!isset($_GET['logout']) && authorized()) {
echo ':-)';
} else
unauthorized();
So this code changes the location by login and logout.
Cross domain CORS with HTTP basic auth
http://todo.loc
Gets the content of http://test.loc with cross domain XHR and displays it.
cross domain ajax<br />
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', "http://test.loc", true);
xhr.withCredentials = true;
xhr.onreadystatechange = function (){
if (xhr.readyState==4) {
document.body.innerHTML += xhr.responseText;
}
};
xhr.send();
</script>
Requires headers by http://test.loc:
Access-Control-Allow-Origin: http://todo.loc
Access-Control-Allow-Credentials: true
Cross scheme CORS with HTTP basic auth
file:///path/x.html
Gets the content of http://test.loc with cross scheme XHR and displays it.
cross scheme ajax<br />
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', "http://test.loc", true);
xhr.withCredentials = true;
xhr.onreadystatechange = function (){
if (xhr.readyState==4) {
document.body.innerHTML += xhr.responseText;
}
};
xhr.send();
</script>
Requires headers by http://test.loc:
Access-Control-Allow-Origin: null
Access-Control-Allow-Credentials: true
Conclusion:
I tested cross-sheme CORS with credentials called from file:// and it works pretty well in firefox, chrome and msie.