Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cors #28

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open

Cors #28

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions sample-proxies/cors/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#CORS Implementation

This sample demonstrates how you can use the CORS policy to
support browsers CORS request.

Cross-Origin Resource Sharing (CORS) is a W3C spec that allows cross-domain communication from the browser.
By building on top of the XMLHttpRequest object, CORS allows developers to work with the same idioms as same-domain requests.

The use-case for CORS is simple.
Imagine the site abc.com has some data that the site xyz.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy.
However, by supporting CORS requests, abc.com can add a few special response headers that allows xyz.com to access the data.

As you can see from this example, CORS support requires coordination between both the server and client.
In the Add-CORS policy , there is a Access-Control-Allow-Headers where we have added an additional entry 'X-Custom-CORS' apart from standard Allow Headers .



# Configure

Update `/setup/setenv.sh` with your environment details

# Import and deploy sample project

To deploy, run `$ sh deploy.sh`

To test via curl, run `$ sh invoke.sh`

Additionally you can test CORS with javascript.
Please edit the index.html file and look for org and env variable . Change it with your settings.

Put it in any web server and access it as
http://localhost/demo/index.html


Trace the functionality in API Management Portal .
You will see two requests - The first one being the OPTIONS request and then the GET request.
Look for Origin Header , OPTION request and some response headers set by OPTIONS request.


# Get help

For assistance, post to the [Apigee Developer Forum](http://support.apigee.com)

Copyright © 2013 Apigee Corporation

Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy
of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Binary file added sample-proxies/cors/apiproxy/.DS_Store
Binary file not shown.
3 changes: 3 additions & 0 deletions sample-proxies/cors/apiproxy/CORS.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<APIProxy revision="1" name="CORS">
</APIProxy>
15 changes: 15 additions & 0 deletions sample-proxies/cors/apiproxy/policies/Add-CORS.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage enabled="true" continueOnError="false" async="false" name="add-cors">
<DisplayName>Add-CORS</DisplayName>
<FaultRules/>
<Properties/>
<Add>
<Headers>
<Header name="Access-Control-Allow-Origin">*</Header>
<Header name="Access-Control-Allow-Headers">origin, x-requested-with, accept,X-Custom-CORS</Header>
<Header name="Access-Control-Allow-Methods">GET, PUT, POST, DELETE</Header>
</Headers>
</Add>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
<AssignTo createNew="false" transport="http" type="response"></AssignTo>
</AssignMessage>
7 changes: 7 additions & 0 deletions sample-proxies/cors/apiproxy/policies/ContentListings.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Javascript timeLimit="1000" enabled="true" continueOnError="false" async="false" name="ContentListings">
<DisplayName>ContentListings</DisplayName>
<FaultRules/>
<Properties/>
<ResourceURL>jsc://contentlisting.js</ResourceURL>
</Javascript>
40 changes: 40 additions & 0 deletions sample-proxies/cors/apiproxy/proxies/default.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ProxyEndpoint name="default">
<Description></Description>
<FaultRules/>
<Flows>
<Flow name="content-listing">
<Description></Description>
<Request>
</Request>
<Response>
<Step>
<FaultRules/>
<Name>ContentListings</Name>
</Step>
</Response>
<Condition>(proxy.pathsuffix MatchesPath &quot;/content-listing&quot;) and (request.verb = &quot;GET&quot;)</Condition>
</Flow>
</Flows>
<PostFlow name="PostFlow">
<Request/>
<Response>
<Step>
<FaultRules/>
<Name>add-cors</Name>
</Step>
</Response>

</PostFlow>
<PreFlow name="PreFlow">
<Request/>
<Response/>
</PreFlow>
<HTTPProxyConnection>
<BasePath>/v1/cors</BasePath>
<Properties/>
<VirtualHost>default</VirtualHost>
<VirtualHost>secure</VirtualHost>
</HTTPProxyConnection>
<RouteRule name="noroute"/>
</ProxyEndpoint>
18 changes: 18 additions & 0 deletions sample-proxies/cors/apiproxy/resources/jsc/contentlisting.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
var books = {
book: []
};


for (var i=0 ; i < 10 ; i++) {

books.book.push({
"id" : i,
"title" : "book title " + i,
"author" : "book author " + i,
"comments" : "book comments " + i
});

}

context.setVariable("response.content", JSON.stringify(books));
context.setVariable("response.header.Content-Type" , "application/json");
125 changes: 125 additions & 0 deletions sample-proxies/cors/demo/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>

var org='apiflix' ;
var env='test' ;

// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}

// Helper method to parse the title tag from the response.
function getTitle(text) {
return text.match('<title>(.*)?</title>')[1];
}

// Make the actual CORS request.
function makeCorsRequest() {

//Please change the org with the org you are deploying
//Please change the env with the env you are deploying

var url = 'http://' + org + '-' + env + '.apigee.net/v1/cors/content-listing';

var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}

xhr.setRequestHeader('X-Custom-CORS', 'Valid CORS');

// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
//var title = getTitle(text);
$("#result").html(text);
//alert('Response from CORS request to ' + text );
};

xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};

xhr.send();
}


// Make the actual CORS request.
function makeBadCorsRequest() {

//Please change the org with the org you are deploying
//Please change the env with the env you are deploying

var url = 'http://$org-$env.apigee.net/v1/cors/content-listing';

var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}

xhr.setRequestHeader('X-Custom-Invalid-CORS', 'Valid CORS');

// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
//var title = getTitle(text);
$("#result").html(text);
//alert('Response from CORS request to ' + text );
};

xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};

xhr.send();
}

$(document).ready(function(){
$("#good").click(function(){
makeCorsRequest();

});

$("#bad").click(function(){
makeBadCorsRequest();

});
});



</script>


</head>
<body>

<input id="good" type="button" value="Send request to and get the result back" />
<br/><br/>
<input id="bad" type="button" value="Send request with invalid header" />
<br/>
<br/>
<p>
<span id="result"></div>
</p>
</body>
</html>
15 changes: 15 additions & 0 deletions sample-proxies/cors/deploy.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/bin/bash

source ../../setup/setenv.sh

echo "Enter your password for the Apigee Enterprise organization $org, followed by [ENTER]:"

read -s password

echo Deploying $proxy to $env on $url using $username and $org

../../tools/deploy.py -n cors -u $username:$password -o $org -h $url -e $env -p / -d ../cors

echo "If 'State: deployed', then your API Proxy is ready to be invoked."

echo "Run 'invoke.sh'"
10 changes: 10 additions & 0 deletions sample-proxies/cors/invoke.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/bin/bash

echo Using org and environment configured in /setup/setenv.sh, $org and $env

source ../../setup/setenv.sh
echo "Making Options request"
curl -X OPTIONS -H "X-Custom-CORS:test" http://$org-$env.apigee.net/v1/cors/content-listing
echo "Making request with header"
curl -H "X-Custom-CORS:Valid Cors" http://$org-$env.apigee.net/v1/cors/content-listing
echo ""