Kev*_*ick 16 c# cors signalr visual-studio-2012 owin
我创建了一个自托管Owin/SignalR应用程序,代码类似于本教程中的代码:
一切正常,但出于安全考虑,我想将其限制为仅允许来自特定远程站点的消息.换句话说,我想替换"app.UseCors(CorsOptions.AllowAll);" 使用代码来限制应用程序仅响应来自我定义的URL的消息,即仅允许来自http://www.remote_site.com等的消息.有没有简单的方法来做到这一点?
作为参考,这是我的SignalR启动类的代码:
using System;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Hosting;
using Owin;
using Microsoft.Owin.Cors;
namespace SignalRSelfHost
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
// How do I only allow a specific URL instead of the "CorsOptions.AllowAll" option?
}
}
}
Run Code Online (Sandbox Code Playgroud)
rad*_*tei 24
以下是Owin Startup该类的完整实现:
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using Microsoft.Owin.Cors;
using System.Web.Cors;
[assembly: OwinStartup(typeof(SignalRSelfHost.Startup))]
namespace SignalRSelfHost
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var policy = new CorsPolicy()
{
AllowAnyHeader = true,
AllowAnyMethod = true,
SupportsCredentials = true
};
policy.Origins.Add("domain"); //be sure to include the port:
//example: "http://localhost:8081"
app.UseCors(new CorsOptions
{
PolicyProvider = new CorsPolicyProvider
{
PolicyResolver = context => Task.FromResult(policy)
}
});
app.MapSignalR();
}
}
}
Run Code Online (Sandbox Code Playgroud)
此外,如果您希望服务器接受域列表,只需将它们添加到Origins.
希望这可以帮助!祝好运!
这是我在上面的评论中提到的代码:
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(_corsOptions.Value);
app.MapSignalR();
}
private static Lazy<CorsOptions> _corsOptions = new Lazy<CorsOptions>(() =>
{
return new CorsOptions
{
PolicyProvider = new CorsPolicyProvider
{
PolicyResolver = context =>
{
var policy = new CorsPolicy();
policy.Origins.Add("http://localhost:8081");
policy.AllowAnyMethod = true;
policy.AllowAnyHeader = true;
policy.SupportsCredentials = true;
return Task.FromResult(policy);
}
}
};
});
}
Run Code Online (Sandbox Code Playgroud)
这有效,但我认为Matei上面的答案更简洁.