How to solve CORs Error - CloudFronts

How to solve CORs Error

Introduction

The cors policy adds cross-origin resource sharing (CORS) support to an operation or an API to allow cross-domain calls from browser-based clients.

CORS allows a browser and a server to interact and determine whether or not to allow specific cross-origin requests (i.e. XMLHttpRequests calls made from JavaScript on a web page to other domains). This allows for more flexibility than only allowing same-origin requests, but is more secure than allowing all cross-origin requests.

You need to enable CORS (cross-origin resource sharing) on your APIs to let the visitors of your portal test the APIs through the built-in interactive console. For more details of this policy refer to:

https://docs.microsoft.com/en-us/azure/api-management/api-management-cross-domain-policies#CORS

https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-developer-portal#cors

Adding CORS Policy in API Management

Step 1:

In your API management Portal go to your API and select all operations and click on Inbound processing.

Step 2:

Apply the Cors Policy as follow in Inbound section and click on save.

<cors>

    <allowed-origins>

        <origin> *</origin>

    </allowed-origins>

    <allowed-methods>

        <method>*</method>

    </allowed-methods>

    <allowed-headers>

        <header>*</header>

    </allowed-headers>

<expose-headers>

<header>*</header>

</expose-headers>

</cors>

Note: This is a general cors policy and can be customized as per requirements.

According to our scenario now we can modify the cors policy to avoid unnecessary access as follows:

<cors>

    <allowed-origins>

        <origin> https://sampleapitest.developer.azure-api.net/</origin>

    </allowed-origins>

    <allowed-methods preflight-result-max-age=”300″>

        <method>GET</method>

        <method>POST</method>

    </allowed-methods>

    <allowed-headers>

        <header>*</header>

    </allowed-headers>

</cors>

Step 3:

This is an optional setup if you want to directly enable cors policy without following the method as mentioned in steps 1 and 2 above.

In your API management portal go to the Portal overview section in the left pane and click on ‘Enable CORS’ button. Click on manually apply it on Global Level to enable CORs at a global level.

Verify your CORs Policy is applied

Step 1: Click on the Developer Portal.

Step 4: Copy the URL at Top and Open in new Brower and click on APIs Tab in Navigation Pane at Top on the Webpage.

Step 5: Select your API.

Step 6: Click on try it option.

Step 7: Enter the Subscription Key and click on send.

Step 8: Note the Response.

Conclusion

Thus we have successfully applied as well as verified the CORs Policy in API management and solved the CORs Error.


Share Story :

Secured By miniOrange