[英]Specify Domain in Owin Startup Class
我創建了一個自托管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?
}
}
}
以下是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> _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);
}
}
};
});
}
這有效,但我認為Matei上面的答案更簡潔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.