在Owin启动类中指定域

我创建了一个自托管Owin / SignalR应用程序,代码类似于本教程中的代码:

SignalR Self Host Tutorial

一切正常,但出于安全考虑,我想将其限制为仅允许来自特定远程站点的消息。 换句话说,我想替换“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? } } } 

以下是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(); } } } 

此外,如果您希望服务器接受域列表,只需将它们添加到Origins

希望这可以帮助! 祝好运!

这是我在上面的评论中提到的代码:

 public class Startup { public void Configuration(IAppBuilder app) { app.UseCors(_corsOptions.Value); app.MapSignalR(); } private static Lazy _corsOptions = new Lazy(() => { 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); } } }; }); } 

这有效,但我认为Matei的上述答案更清晰,更简单。