【问题标题】:.Net core2 CORS - How SetIsOriginAllowed works?.Net core2 CORS - SetIsOriginAllowed 如何工作?
【发布时间】:2018-05-29 22:38:21
【问题描述】:

希望允许从不同站点访问我的 API。为此有:

services
    .AddCors(options =>
    {
        options.AddPolicy(PolicyName, builder =>
        {
            builder
                .SetIsOriginAllowedToAllowWildcardSubdomains()
                .WithOrigins(
                    "http://*.my-api.com",
                    "http://*.my-api.service"
                )
...

这似乎不允许 httpS 或当我在请求中指定端口时。

例如: https://www.my-api.com:3000

Thought 可以用 SetIsOriginAllowed() 代替 WithOrigins

services
    .AddCors(options =>
    {
        options.AddPolicy(PolicyName, builder =>
        {
            builder
                .SetIsOriginAllowed(IsOriginAllowed)

其中 IsOriginAllowed 函数定义为:

private static bool IsOriginAllowed(string host)
{
    var corsOriginAllowed = new[] { "my-api.com", "my-api.service" };

    return corsOriginAllowed.Any(origin =>
        Regex.IsMatch(host, $@"^http(s)?://.*{origin}(:[0-9]+)?$", RegexOptions.IgnoreCase));
}

但这根本不起作用,即使是正则表达式也会在我想要的时候返回 true。

有谁知道为什么这不起作用,并且可以告诉我允许 httpS 的正确方法(除了使用 httpS 和不同端口复制 WithOrigins() 中的所有域。

谢谢

【问题讨论】:

    标签: asp.net-core cors


    【解决方案1】:

    SetIsOriginAllowed() 确实有效。正在使用 Postman 进行测试,据说 Postman 并不关心从服务器返回的标头。执行 Cors 标头的是浏览器。

    为了测试在一个测试站点下使用下面的 javascript 正确创建了一个小 html 页面

    <html>
        <script>
            fetch('http://test.com:5000/v2/campaign/hallo3').then(function(response) {
                return response.json();
            }).then(function(j) {            
    	        alert(JSON.stringify(j));
            });
        </script>
    </html>

    当域不包含在 Cors 允许列表中时,浏览器不显示 API 的返回值

    将测试域添加到允许域列表后,浏览器显示数据并获取内容 Cors 标头

    另一个问题是仅使用 SetIsOriginAllowed() 服务器没有发送“Vary”标头。必须同时设置:

    .SetIsOriginAllowed(IsOriginAllowed)
    .WithOrigins(corsOriginAllowed)
    

    【讨论】:

    • 我看到您使用 corsOriginAllowed 作为代码中定义的变量。我们可以使用 appsettings.json 中的“AllowedHosts”配置吗?这个配置“allowedHosts”有什么用。我在互联网上四处查找,并没有得到一个明确的答案或对其目的的解释。你能帮我解决这个问题吗@Riga
    猜你喜欢
    • 1970-01-01
    • 2021-01-08
    • 2018-07-28
    • 2020-04-12
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 2017-08-19
    相关资源
    最近更新 更多