support for multiple CORS policies in APIM

SdM 1 Reputation point
2020-06-23T12:06:41.363+00:00

I would like to define a CORS policy at Global level (to allow a developer portal to offer a swaggerUI) as well as at API level (to allow custom browser apps to call specific APIs).
Today, the first CORS policy found after unrolling the different levels is the one used by the APIM (right?) which makes it difficult to implement my scenario.

Is there a good work-around today ?

If not, could it be possible to add a logic similar to the set-header exists-action="override | skip | append | delete" that would allow to have multiple CORS policy one after the other (from different levels for instance) and decide of the final CORS policy interpretation:

  • overwrite (meaning "replace any previous CORS defined before")
  • skip (meaning "apply only if no CORS defined before", current behavior as only the first CORS is used)
  • append (try this CORS if previous CORS have failed)
    (high level idea, not sure about the intricacies of this logic)
Azure API Management
Azure API Management
An Azure service that provides a hybrid, multi-cloud management platform for APIs.
1,943 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Samara Soucy - MSFT 21 Reputation points
    2020-06-30T19:17:16.897+00:00

    You could use expressions to conditionally set the value on the global scope.

    For example, if I know that the template for the swaggerUI on all my APIs is going to be "/swagger" I can use that to determine how to set the headers on the global scope.

    11007-cors1.png

    I can go into the code editor for my global scope and add my CORS policy like this:

    <cors>  
    	<allowed-origins>  
    		<origin>@{  
    			bool swaggerPage = context.Operation.UrlTemplate == "/swagger";  
    			if(swaggerPage) {  
    				return "*";  
    			}  
    			else {  
    				return null;  
    			}  
    		}</origin>  
    	</allowed-origins>  
    	<allowed-methods>  
    		<method>GET</method>  
    		<method>POST</method>  
    	</allowed-methods>  
    </cors>  
    

    Expressions are created using C# 7, though only a subset of types are available. There is a lot of flexibility here to adjust your policies based on the request context. You can read about the options available in the docs: https://learn.microsoft.com/en-us/azure/api-management/api-management-policy-expressions