Can someone provide a CorsPolicy implementation wi

2019-04-11 10:50发布

Referring to the SignalR Hubs API Guide

indicates the following information in the configuration comments:

// Setup the CORS middleware to run before SignalR.
// By default this will allow all origins. You can 
// configure the set of origins and/or http verbs by
// providing a cors options with a different policy.
map.UseCors(CorsOptions.AllowAll);

however, the Origins property of System.Web.CorsPolicy has a private setter, no constructor that allows origins to be injected, and no exposed setter method. With regards to the Origins list, it seems to only expose an "AllowAllOrigins" property and then a useless Origins getter that is only reflecting out the empty List that is constructed during CorsPolicy construction.


Of particular note, the default app.UseCors(CorsOptions.AllowAll) setting is entirely incoherent. By its own tooltip, it is "A policy that allows all headers, all methods, any origin, and supports credentials."

A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true

My configuration is currently the "stupid simple" SignalR config

public void Configuration(IAppBuilder app)
{                
    app.UseCors(CorsOptions.AllowAll);
    app.MapSignalR();
}

Can anyone provide a Microsoft.Owin.Cors.CorsMiddleware example that would reimplement the "AllowAll" Options with an explicit whitelist for Access-Control-Allow-Origin?

1条回答
再贱就再见
2楼-- · 2019-04-11 11:25

Have you looked at the source for CorsOptions.AllowAll? It shows how the CorsOptions is created. You could do something like

var policy = new CorsPolicy
{
    AllowAnyHeader = true,
    AllowAnyMethod = true,
    AllowAnyOrigin = false, // False by default, just left it here.
    SupportsCredentials = true
};

policy.Origins.Add("http://foo.example.com");

app.UseCors(new CorsOptions
{
    PolicyProvider = new CorsPolicyProvider
    {
        PolicyResolver = context => Task.FromResult(policy)
    }
});

As you can see, you set the PolicyResolver property, which is a Func<IOwinRequest, Task<CorsPolicy>>. Based on the IOwinContext (for the current request), you need to return a CorsPolicy (also, see its source). This should have the properties you need to fine tune your policy. The list properties have private setters (probably to avoid potential null pointers), but they're all initialized in the default constructor, so you should be able to add to them.

查看更多
登录 后发表回答