首页 > 解决方案 > 是否可以在 Asp Net Core Api 中使用通配符为部分随机 url 设置 cors 规则?

问题描述

我有一个 Asp Net Core (3.1) Api,我在其中指定了这样的 cors 策略:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy(name: "MyPolicy",
            builder =>
            {
                builder.WithOrigins("https://myurl.com",
                                   )
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials())
            });
    });
}

但是,我希望能够允许任何包含“myurl”的来源,即使它有不同的开始或结束,只要它包含“myurl”。

例如,应该允许 https://adifferentstartthenmyurl.com 例如,最好也应该允许https://myurladifferentend.com 。

这在 net core 3.1 cors 规则中是否支持?是否可以指定这样的 cors 策略?

我希望能够使用类似的东西:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy(name: "MyPolicy",
            builder =>
            {
                builder.WithOrigins("https://*myurl*.com",
                                   )
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials())
            });
    });
}

使用 * 作为通配符说明符。

标签: c#.net-corecors

解决方案


CORS 只放宽严格的同源政策

不可能,因为它会禁用 CORS。在 url 中使用通配符,CORS 将被禁用,因为任何人都可以为跨域攻击注册额外的域。

关于 CORS


推荐阅读