2

Using the CorsFeature plugin, how can I support multiple origin domains? I'm not talking about the wildcard "*" here. I'm talking about passing in a list of more than one origins: "http://firstdomain.com, http://seconddomain.com".

Andrew Young
  • 1,779
  • 1
  • 13
  • 27

1 Answers1

5

ServiceStack's CorsFeature is just a simple plugin that adds CORS Headers to ServiceStack's Global Response Headers. It supports specifying a number of hosts (or * wildcard), e.g:

Plugins.Add(new CorsFeature(
    allowOriginWhitelist = new[]{ "http://domain1.com", "http://domain2.com" }, 
    string allowedMethods = DefaultMethods, 
    string allowedHeaders = DefaultHeaders, 
    bool allowCredentials = false));

If you need more customization, then you can simply skip the feature and just add register as many customized response headers as you wish, e.g:

public override void Configure(Container container)
{
    //Permit Cross Origin Resource Sharing for multiple Origins:
    base.SetConfig(new HostConfig
    {
        GlobalResponseHeaders = {
            { "Access-Control-Allow-Origin", "http://domain.com" },
            { "Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS" },
            { "Access-Control-Allow-Headers", "Content-Type" },
        },
    });
}

Or using a Global Request or PreRequest Filter:

public override void Configure(Container container)
{
    var originWhitelist = new[]{ "http://domain1.com", "http://domain2.com" };

    this.PreRequestFilters.Add((httpReq, httpRes) => {
        var origin = httpReq.Headers.Get("Origin");
        if (originWhitelist.Contains(origin))
        {
            httpRes.AddHeader(HttpHeaders.AllowOrigin, origin);
        }
        httpRes.AddHeader(HttpHeaders.AllowMethods, "GET, POST, PUT, OPTIONS");
        httpRes.AddHeader(HttpHeaders.AllowHeaders, "Content-Type");
    });
}
Community
  • 1
  • 1
mythz
  • 141,670
  • 29
  • 246
  • 390
  • the second method doesn't work because you're adding the same key twice. –  Apr 01 '14 at 14:42
  • how can I add more than one origin using the 2nd approach? –  Apr 02 '14 at 08:48
  • @iwayneo You can't because as you say, it's a dictionary that doesn't allow multiple keys, I've added an example using a PreRequest filter as an alternative. – mythz Apr 02 '14 at 09:06
  • Hmmm. using this method I get: The 'Access-Control-Allow-Origin' header contains multiple values 'http://sdsdsdf.com, http://sdfsdfsdf.com', but only one is allowed. Origin 'http://sdsdsdf.com' is therefore not allowed access. –  Apr 02 '14 at 10:03
  • @iwayneo ok yeah updated, this is basically what the [CorsFeature](https://github.com/ServiceStack/ServiceStack/blob/master/src/ServiceStack/CorsFeature.cs) plugin does. – mythz Apr 02 '14 at 10:16
  • should that be if (!originWhitelist.Contains(origin)) –  Apr 02 '14 at 11:16
  • @iwayneo no, it's a whitelist? – mythz Apr 02 '14 at 17:25