Roberto Fuentes
fullstack devops
Cross-Origin Resource Sharing
to learn
what was the first browser to support?
Chrome 4.0
*preflight
client = browser = server
lifecycle
MUST
Preflight Requests (asking for permission)
Preflight Requests (asking for permission)
How NOT to trigger a preflight
Preflight Requests (asking for permission)
Triggering preflight
onloadstart
onprogress
onabort
onerror
onload
ontimeout
onloadend
onreadystatechange
Events Handlers
Response Properties
status
statusText
response
responseText
responseXML
Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma
Can only read these Headers*:
*unless server explicitly states otherwise
Cookies are not sent by default*
withCredentials = true;
user credentials such as cookies,
basic authentication information, or
Secure Sockets Layer (SSL) certificates
*server must allow cookies
fetch('http://localhost:4000/status').then(function(response) {
return response.json();
}).then(function(stuff) {
console.log(stuff);
});
GET
fetch('http://localhost:4000/posts').then(function(response) {
return response.json();
}).then(function(stuff) {
console.log(stuff);
});
GET
var msg = 'This is another blog post';
fetch('http://localhost:4000/posts', {
method: 'post',
mode: 'cors',
body: JSON.stringify({
6: msg
})
}).then(function(response) {
return response.json();
}).then(function(stuff) {
console.log(stuff);
});
POST
fetch('http://localhost:4000/posts/2', {
method: 'delete'
}).then(function(response) {
console.log('cool');
})
DELETE
const whitelist = [
config.rootUrl,
config.ereaderUrl,
config.ereaderUrlDev,
config.ereaderUrlTest,
config.cors.bfwpub,
config.cors.macmillanHighered,
config.cors.macmillanTech,
config.cors.rls
];
const isPreflight = function(req) {
const isHttpOptions = req.method === 'OPTIONS';
const hasOriginHeader = req.headers['origin'];
const hasRequestMethod = req.headers['access-control-request-method'];
return isHttpOptions && hasOriginHeader && hasRequestMethod;
};
const passThrough = ['GET', 'HEAD'];
const allowOnly = ['POST', 'PUT'];
function allowOrigin(ctx) {
const { reqId, request } = ctx;
if (isPreflight(request)) {
const hasRequestMethod = request.headers['access-control-request-method'];
if (!allowOnly.includes(hasRequestMethod)) {
return;
}
}
if (request && request.method && passThrough.includes(request.method)) {
return '*';
}
if (request && request.header && request.header.origin &&
!whitelist.includes(request.header.origin) && !request.header.origin.match(/\.mldev.cloud/)) {
logger.error('CORS -- invalid origin', { reqId, origin: request.header.origin });
ctx.status = 400;
return;
}
return request.header.origin || '*';
By Roberto Fuentes