Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Add usable CORS policy in my API proxy when using OAuth 2.0

Not applicable

I add a OAuth Verify Token policy in the sample proxy, weatherxml.

After that, I use POSTMAN to send request to the proxy with bearer tokens in request header and it work well.

However, when I changed to jQuery in my browser, the CORS problems happens, both in my Chrome and Firefox.

My code is like this:

    $.ajax({
        type: "GET",
        url: "http://{my-org}.apigee.net/v1/weatherxml/forecastrss?w=12797282",
        //contentType: "application/x-www-form-urlencoded",
        beforeSend: function(xhr) {
            xhr.withCredentials = true;
            xhr.setRequestHeader('Authorization', 'bearer '+ access_token);
        },
        success: function(data) {
            console.log("SUCCESS IN CHECK POINT 2");
            console.log(data);
        },
        error: function(data) {
            console.log("FAILED IN CHECK POINT 2");
        }
    }).done( function(msg) {
        console.log("CHECK POINT 2 DONE!");
    });

The error in the console in chrome is:

XMLHttpRequest cannot load http://{my-org}.apigee.net/v1/weatherxml/forecastrss?w=12797282. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

I feel it's wired because after I add a allow CORS policy in my oauth proxy, it indeed returns the access token when I request it using jQuery in my browser.

I've tried to add the policy in every flow in every proxy and target endpoint but my jQuery still doesn't work. I also tried to add header, or change to jsonp in the code, but they are not work.

The CORS policy I added is:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true" name="Add-CORS">
    <DisplayName>Add CORS</DisplayName>
    <FaultRules/>
    <Properties/>
    <Add>
        <Headers>
            <Header name="Access-Control-Allow-Origin">*</Header>
            <Header name="Access-Control-Max-Age">3628800</Header>
            <Header name="Access-Control-Allow-Headers">origin, x-requested-with, accept</Header>
            <Header name="Access-Control-Allow-Methods">GET, PUT, POST, DELETE</Header>
        </Headers>
    </Add>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
    <AssignTo createNew="false" transport="http" type="response"/>
</AssignMessage>

Could anyone help please?

2 14 7,337
14 REPLIES 14