Fix CORS when Authorization header is present

This commit is contained in:
Filip Gralinski 2020-12-22 12:31:30 +01:00
parent 725f3fae04
commit 0e814d3952
2 changed files with 42 additions and 2 deletions

View File

@ -146,8 +146,8 @@ makeApplication foundation = do
-- Create the WAI application and apply middlewares -- Create the WAI application and apply middlewares
appPlain <- toWaiAppPlain foundation appPlain <- toWaiAppPlain foundation
return $ logWare $ defaultMiddlewaresNoLogging $ simpleCors appPlain return $ logWare $ defaultMiddlewaresNoLogging $ myCors appPlain
where myCors = cors (const $ Just (simpleCorsResourcePolicy {corsMethods = ["GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"], corsRequestHeaders = ["Authorization"]}))
makeLogWare :: App -> IO Middleware makeLogWare :: App -> IO Middleware
makeLogWare foundation = makeLogWare foundation =
mkRequestLogger def mkRequestLogger def

View File

@ -43,7 +43,42 @@
req.send(); req.send();
}; };
function testCors() {
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Most browsers.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// IE8 & IE9
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
xhr.setRequestHeader('Authorization', 'Bearer ' +
keycloak.token);
//xhr.setRequestHeader('Xyz', 'Blabla');
xhr.setRequestHeader('Accept', 'application/json');
return xhr;
};
var url = 'http://127.0.0.1:3000/api/list-challenges';
var method = 'GET';
var xhr = createCORSRequest(method, url);
xhr.onload = function() {
alert("OK");
};
xhr.onerror = function() {
alert("NOT OK")
};
xhr.send();
}
</script> </script>
</head> </head>
<body onload="initKeycloak()"> <body onload="initKeycloak()">
@ -55,5 +90,10 @@
<p><button onclick="loadData('challenge-my-submissions/retroc2')">Other test</button></p> <p><button onclick="loadData('challenge-my-submissions/retroc2')">Other test</button></p>
<p><button onclick="loadData('list-challenges')">Yet another
test</button></p>
<p><button onclick="testCors()">CORS</button></p>
</body> </body>
</html> </html>