在Owin启动类中指定域

本文关键字:Owin 启动 | 更新日期: 2023-09-27 18:07:57

我创建了一个自托管的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启动类中指定域

下面是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上面的答案更清晰更简单。