.Net Core 配置CORS以同时允许所有子域和所有本地主机端口 [英] .Net Core Configure CORS to allow all subdomains and all localhost ports at the same time

查看:32
本文介绍了.Net Core 配置CORS以同时允许所有子域和所有本地主机端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想允许来自所有内部网站 (*.myintra.net) 和所有 localhost 端口的 CORS 请求到一个通用的内部 API(当我们正在 IIS Express 本地调试各种应用程序,即 http://localhost:12345http://localhost:54321 等).

I would like to allow CORS requests to a common internal API from all internal websites (*.myintra.net) and also from all localhost ports (for when we are debugging various apps locally in IIS Express, i.e. http://localhost:12345, http://localhost:54321, etc).

这个答案向我展示了如何使用 SetIsOriginAllowedToAllowWildcardSubdomains() 来允许所有子域.

This answer shows me how to use SetIsOriginAllowedToAllowWildcardSubdomains() to allow all subdomains.

这个答案 向我展示了如何使用 允许任何 localhost 端口SetIsOriginAllowed() 委托函数.

This answer shows me how to allow any localhost port by using a SetIsOriginAllowed() delegate function.

但是,这些选项似乎不能一起使用.我的配置:

However, it seems that these options do not work together. My configuration:

private bool AllowLocalhost(string origin)
{
    var uri = new Uri(origin);
    return (uri.Host == "localhost");
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        string[] corsList = "https://*.myintra.net,https://some.specificurl.com".Split(",");
        options.AddPolicy("CorsPolicy", builder =>
        {
            builder
            .WithOrigins(corsList.ToArray())
            .SetIsOriginAllowedToAllowWildcardSubdomains()
            .SetIsOriginAllowed(origin => AllowLocalhost(origin)) // disallows calls from myapp.myintra.net since it doesn't uri.Host match "localhost"
            ...();
        });
    });
    ...
}

我可以交换配置的顺序:

I can swap the order of the configuration:

.SetIsOriginAllowed(origin => AllowLocalhost(origin))
.SetIsOriginAllowedToAllowWildcardSubdomains()

但是 AllowLocalhost() 函数永远不会被调用.我想一次只有一个工作是有道理的,因为第一个检查可能返回 true,只有第二个返回 false.

But then the AllowLocalhost() function is never called. I suppose it makes sense that only one works at a time, since the first check may return true, only to have the second one return false.

理想情况下,我想要一个解决方案,我不需要在我的 AllowLocalhost() 函数中重新实现 allow wildcard 逻辑.

Ideally, I'd like a solution that doesn't involve me having to reimplement the allow wildcard logic inside of my AllowLocalhost() function.

另外值得注意的是,我真的只在开发环境中需要这个.生产将需要允许通配符,但不允许 localhost 无论端口如何.

Also worth noting that I really only need this in a development environment. Production would need to allow wildcards, but disallow localhost no matter the port.

推荐答案

我就是这样实现的:

我正在使用 IsOriginAllowed 检查来源:

I'm checking the origin with the IsOriginAllowed:

    public void ConfigureServices(IServiceCollection services)
    {
        // ...

        services.AddCors(options =>
        {
            options.AddPolicy(name: "AllowedCorsOrigins",
                builder =>
                {
                    builder
                        .SetIsOriginAllowed(IsOriginAllowed)
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials();
                });
        });
        // ...

一如既往地激活 Cors:

Activate Cors as always:

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
        // ...
        app.UseCors("AllowedCorsOrigins");
        // ...

这就是方法,应该可以解决问题.接受来自 example.com 和 another-example.com 的所有请求,包括所有子域.如果 ASPNETCORE_ENVIRONMENT 正在运行的服务包含DEV"还允许本地主机.

That's the method, that should do the trick. Accept all requests from example.com and another-example.com including all subdomains. And if the ASPNETCORE_ENVIRONMENT the Service is running contains "DEV" than also allow localhost.

private static bool IsOriginAllowed(string origin)
{
    var uri = new Uri(origin);
    var env = System.Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "n/a";

    var isAllowed = uri.Host.Equals("example.com", StringComparison.OrdinalIgnoreCase)
                    || uri.Host.Equals("another-example.com", StringComparison.OrdinalIgnoreCase)
                    || uri.Host.EndsWith(".example.com", StringComparison.OrdinalIgnoreCase)
                    || uri.Host.EndsWith(".another-example.com", StringComparison.OrdinalIgnoreCase);
    if (!isAllowed && env.Contains("DEV", StringComparison.OrdinalIgnoreCase))
        isAllowed = uri.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase);

    return isAllowed;
}

这篇关于.Net Core 配置CORS以同时允许所有子域和所有本地主机端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆