Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS enabled Web API fails to add header

I am using the DynamicPolicyProviderFactory as described here. Below is my version of the DynamicPolicyProviderFactory:

public class DynamicPolicyProviderFactory : ICorsPolicyProviderFactory
{
    private readonly HashSet<Regex> _allowed;

    public DynamicPolicyProviderFactory(IEnumerable allowedOrigins)
    {
        _allowed = new HashSet<Regex>();

        foreach (string pattern in allowedOrigins.Cast<string>()
            .Select(Regex.Escape)
            .Select(pattern => pattern.Replace("*", "w*")))
        {
            _allowed.Add(new Regex(pattern, RegexOptions.IgnoreCase));
        }

        if (_allowed.Count >= 1)
            return;

        //if nothing is specified, we assume everything is.
        _allowed.Add(new Regex(@"https://\w*", RegexOptions.IgnoreCase));
        _allowed.Add(new Regex(@"http://\w*", RegexOptions.IgnoreCase));
    }

    public ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request)
    {
        var route = request.GetRouteData();
        var controller = (string)route.Values["controller"];
        var corsRequestContext = request.GetCorsRequestContext();
        var originRequested = corsRequestContext.Origin;
        var policy = GetPolicyForControllerAndOrigin(controller, originRequested);
        return new CustomPolicyProvider(policy);
    }

    private CorsPolicy GetPolicyForControllerAndOrigin(string controller, string originRequested)
    {
        // Do lookup to determine if the controller is allowed for
        // the origin and create CorsPolicy if it is (otherwise return null)

        if (_allowed.All(a => !a.Match(originRequested).Success))
            return null;

        var policy = new CorsPolicy();
        policy.Origins.Add(originRequested);
        policy.Methods.Add("GET");
        policy.Methods.Add("POST");
        policy.Methods.Add("PUT");
        policy.Methods.Add("DELETE");
        return policy;
    }
}

public class CustomPolicyProvider : ICorsPolicyProvider
{
    private readonly CorsPolicy _policy;

    public CustomPolicyProvider(CorsPolicy policy)
    {
        this._policy = policy;
    }

    public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return Task.FromResult(this._policy);
    }
}

My call to register the cors win the WebApiConfig.cs

 config.EnableCors();
 config.SetCorsPolicyProviderFactory(new DynamicPolicyProviderFactory(Settings.Default.AllowedDomains));

And my application settings being passed:

<MyApp.Properties.Settings>
  <setting name="AllowedDomains" serializeAs="Xml">
    <value>
      <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <string>http://localhost</string>
        <string>http*://*.domain1.com</string>
        <string>http*://*.domain2.com</string>
      </ArrayOfString>
    </value>
  </setting>
</MyApp.Properties.Settings>

Despite these settings, the Access-Control-Allow-Origin header is not present on my responses if I make a request from http://mg.domain1.com to http://localhost. I am using Web Api 2.2 and Microsoft.AspNet.Cors 5.2.2.

edit: I have found that if I use the EnableCors attribute on the controller, or enable it globally (config.EnableCors(new EnableCorsAttribute("*", "*", "*"));) it works, so it must be something with my dynamic factory. The frustrating thing is, the DynamicPolicyProvider is copy/pasted from another project I am using that works fine.

edit 2: Success!...I enabled tracing and found the error

 The collection of headers 'accept,content-type' is not allowed

So I just edited the GetPolicyForControllerAndOrigin method to allow them. Now everything works, except I am confused because I did not have to jump through this hoop in my other project (the one I copied the DynamicPolicyProviderFactory from).

like image 974
Mike_G Avatar asked Nov 17 '14 18:11

Mike_G


1 Answers

Enable tracing in the app. You should see an error

The collection of headers 'accept,content-type' is not allowed

Just add these to the allowed headers for the policy and everything should work.

like image 103
Mike_G Avatar answered Sep 28 '22 22:09

Mike_G