Can someone provide a CorsPolicy implementation with an explicit Origins list?

拈花ヽ惹草 提交于 2019-12-06 07:59:30

问题


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:


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.



来源:https://stackoverflow.com/questions/26657645/can-someone-provide-a-corspolicy-implementation-with-an-explicit-origins-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!