本文介绍如何在 asp.net core 的应用程序中启用 cors。

浏览器安全可以防止网页向其他域发送请求,而不是为网页提供服务。 此限制称为相同源策略。 同一源策略可防止恶意站点读取另一个站点中的敏感数据。 有时,你可能想要允许其他站点对你的应用进行跨域请求。 有关详细信息,请参阅mozilla cors 一文。

跨源资源共享(cors):

  • 是一种 w3c 标准,可让服务器放宽相同的源策略。
  • 不是一项安全功能,cors 放宽 security。 api 不能通过允许 cors 来更安全。 有关详细信息,请参阅cors 的工作原理。
  • 允许服务器明确允许一些跨源请求,同时拒绝其他请求。
  • 比早期的技术(如jsonp)更安全且更灵活。

查看或下载示例代码()

同一原点

如果两个 url 具有相同的方案、主机和端口(rfc 6454),则它们具有相同的源。

这两个 url 具有相同的源:

  • https://example.com/foo.html
  • https://example.com/bar.html

这些 url 的起源不同于前两个 url:

  • https://example.net – 个不同的域
  • https://www.example.com/foo.html – 个不同的子域
  • http://example.com/foo.html – 个不同的方案
  • https://example.com:9000/foo.html – 个不同端口

比较来源时,internet explorer 不会考虑该端口。

具有命名策略和中间件的 cors

cors 中间件处理跨域请求。 以下代码通过指定源为整个应用启用 cors:

 
public class startup
{
    public startup(iconfiguration configuration)
    {
        configuration = configuration;
    }

    readonly string myallowspecificorigins = "_myallowspecificorigins";

    public iconfiguration configuration { get; }

    public void configureservices(iservicecollection services)
    {
        services.addcors(options =>
        {
            options.addpolicy(myallowspecificorigins,
            builder =>
            {
                builder.withorigins("http://example.com",
                                    "http://www.contoso.com");
            });
        });

        services.addmvc().setcompatibilityversion(compatibilityversion.version_2_2);
    }

    public void configure(iapplicationbuilder app, ihostingenvironment env)
    {
        if (env.isdevelopment())
        {
            app.usedeveloperexceptionpage();
        }
        else
        {
            app.usehsts();
        }

        app.usecors(myallowspecificorigins); 

        app.usehttpsredirection();
        app.usemvc();
    }
}

 

前面的代码:

  • 将策略名称设置为 “_myallowspecificorigins”。 策略名称为任意名称。
  • 调用 usecors 扩展方法,这将启用 cors。
  • 使用调用 addcors。 lambda 采用 @no__t 0 对象。 本文稍后将介绍,如 withorigins

@no__t-0 方法调用将 cors 服务添加到应用的服务容器:

 

public void configureservices(iservicecollection services)
{
    services.addcors(options =>
    {
        options.addpolicy(myallowspecificorigins,
        builder =>
        {
            builder.withorigins("http://example.com",
                                "http://www.contoso.com");
        });
    });

    services.addmvc().setcompatibilityversion(compatibilityversion.version_2_2);
}

 

有关详细信息,请参阅本文档中的cors 策略选项。

@no__t-0 方法可以链接方法,如以下代码所示:

 

public void configureservices(iservicecollection services)
{
    services.addcors(options =>
    {
        options.addpolicy(myallowspecificorigins,
        builder =>
        {
            builder.withorigins("http://example.com",
                                "http://www.contoso.com")
                                .allowanyheader()
                                .allowanymethod();
        });
    });

    services.addmvc().setcompatibilityversion(compatibilityversion.version_2_2);
}

 

注意: url不得包含尾随斜杠(/)。 如果 url 以 / 终止,比较将返回 false,并且不返回任何标头。

将 cors 策略应用到所有终结点

以下代码通过 cors 中间件将 cors 策略应用到所有应用终结点:

public void configure(iapplicationbuilder app, ihostingenvironment env)
{
    // preceding code ommitted.
    app.userouting();

    app.usecors();

    app.useendpoints(endpoints =>
    {
        endpoints.mapcontrollers();
    });

    // following code ommited.
}

 

 警告

通过终结点路由,cors 中间件必须配置为在对 @no__t 和 useendpoints 的调用之间执行。 配置不正确将导致中间件停止正常运行。

请参阅在 razor pages、控制器和操作方法中启用 cors,以在页面/控制器/操作级别应用 cors 策略。

有关测试上述代码的说明,请参阅测试 cors 。

 

使用终结点路由启用 cors

使用终结点路由,可以根据每个终结点启用 cors,使用 @no__t 的扩展方法集。

app.useendpoints(endpoints =>
{
  endpoints.mapget("/echo", async context => context.response.writeasync("echo"))
    .requirecors("policy-name");
});

 

同样,也可以为所有控制器启用 cors:

app.useendpoints(endpoints => { endpoints.mapcontrollers().requirecors("policy-name"); }); 


使用属性启用 cors

@no__t-1enablecors @ no__t属性提供了一种用于全局应用 cors 的替代方法。 @no__t-0 特性可为选定的终结点(而不是所有终结点)启用 cors。

使用 @no__t 指定默认策略,并 [enablecors("{policy string}")] 指定策略。

@no__t-0 特性可应用于:

  • razor 页 pagemodel
  • 控制器
  • 控制器操作方法

您可以将不同的策略应用于控制器/页面模型/操作,[enablecors] 属性。 将 [enablecors] 属性应用于控制器/页面模型/操作方法,并在中间件中启用 cors 时,将应用这两种策略。 建议不要结合策略。 使用同一个应用中的 [enablecors] 特性或中间件。

下面的代码将不同的策略应用于每个方法:

[route("api/[controller]")]
[apicontroller]
public class widgetcontroller : controllerbase
{
    // get api/values
    [enablecors("anotherpolicy")]
    [httpget]
    public actionresult<ienumerable<string>> get()
    {
        return new string[] { "green widget", "red widget" };
    }

    // get api/values/5
    [enablecors]        // default policy.
    [httpget("{id}")]
    public actionresult<string> get(int id)
    {
        switch (id)
        {
            case 1:
                return "green widget";
            case 2:
                return "red widget";
            default:
                return notfound();
        }
    }
}

 

以下代码创建 cors 默认策略和名为 "anotherpolicy" 的策略:

 
public class startupmultipolicy
{
    public startupmultipolicy(iconfiguration configuration)
    {
        configuration = configuration;
    }

    public iconfiguration configuration { get; }

    public void configureservices(iservicecollection services)
    {
        services.addcors(options =>
        {
            options.adddefaultpolicy(
                builder =>
                {
                   
                    builder.withorigins("http://example.com",
                                        "http://www.contoso.com");
                });

            options.addpolicy("anotherpolicy",
                builder =>
                {
                    builder.withorigins("http://www.contoso.com")
                                        .allowanyheader()
                                        .allowanymethod();
                });

        });

        services.addmvc().setcompatibilityversion(compatibilityversion.version_2_2);
    }

    public void configure(iapplicationbuilder app, ihostingenvironment env)
    {
        if (env.isdevelopment())
        {
            app.usedeveloperexceptionpage();
        }
        else
        {
            app.usehsts();
        }

        app.usehttpsredirection();
        app.usemvc();
    }
}

 

禁用 cors

@no__t-1disablecors @ no__t-2属性对控制器/页模型/操作禁用 cors。

cors 策略选项

本部分介绍可在 cors 策略中设置的各种选项:

  • 设置允许的 http 方法

startup.configureservices 中调用 addpolicy。 对于某些选项,最好先阅读cors 如何工作部分。

设置允许的来源

allowanyorigin – 允许所有来源的 cors 请求和任何方案(http 或 https)。 allowanyorigin 不安全,因为任何网站都可以向应用程序发出跨域请求。

 备注

指定 @no__t 0 和 @no__t 为不安全配置,可能导致跨站点请求伪造。 使用这两种方法配置应用时,cors 服务将返回无效的 cors 响应。

allowanyorigin 会影响预检请求和 @no__t 标头。 有关详细信息,请参阅部分。

setisoriginallowedtoallowwildcardsubdomains – 将策略的 @no__t 设置为在评估是否允许源时允许源与配置的通配符域匹配的函数。

 

options.addpolicy("allowsubdomain",
    builder =>
    {
        builder.withorigins("https://*.example.com")
            .setisoriginallowedtoallowwildcardsubdomains();
    });

 

设置允许的 http 方法

allowanymethod:

  • 允许任何 http 方法:
  • 影响预检请求和 @no__t 0 标头。 有关详细信息,请参阅部分。

设置允许的请求标头

若要允许在 cors 请求中发送特定标头(称为作者请求标头),请调用 withheaders 并指定允许的标头:

 

options.addpolicy("allowheaders",
    builder =>
    {
        builder.withorigins("http://example.com")
               .withheaders(headernames.contenttype, "x-custom-header");
    });

 

若要允许所有作者请求标头,请调用 allowanyheader:

 

options.addpolicy("allowallheaders",
    builder =>
    {
        builder.withorigins("http://example.com")
               .allowanyheader();
    });

此设置会影响预检请求和 @no__t 0 标头。 有关详细信息,请参阅部分。

仅当在 access-control-request-headers 中发送的标头与 withheaders 中指定的标头完全匹配时,才可以使用 cors 中间件策略与 withheaders 指定的特定标头匹配。

例如,考虑按如下方式配置的应用:

 app.usecors(policy => policy.withheaders(headernames.cachecontrol)); 


cors 中间件使用以下请求标头拒绝预检请求,因为 withheaders 中未列出 content-language (headernames):

access-control-request-headers: cache-control, content-language

应用返回200 ok响应,但不会向后发送 cors 标头。 因此,浏览器不会尝试跨域请求。

设置公开的响应标头

默认情况下,浏览器不会向应用程序公开所有的响应标头。 有关详细信息,请参阅w3c 跨域资源共享(术语):简单的响应标头。

默认情况下可用的响应标头包括:

  • cache-control
  • content-language
  • content-type
  • expires
  • last-modified
  • pragma

cors 规范将这些标头称为简单的响应标头。 若要使其他标头可用于应用程序,请调用 withexposedheaders:

 

options.addpolicy("exposeresponseheaders",
    builder =>
    {
        builder.withorigins("http://example.com")
               .withexposedheaders("x-custom-header");
    });

 

跨域请求中的凭据

凭据需要在 cors 请求中进行特殊处理。 默认情况下,浏览器不会使用跨域请求发送凭据。 凭据包括 cookie 和 http 身份验证方案。 若要使用跨域请求发送凭据,客户端必须将 xmlhttprequest.withcredentials 设置为 true

直接使用 @no__t:

var xhr = new xmlhttprequest();
xhr.open('get', 'https://www.example.com/api/test');
xhr.withcredentials = true;

 

使用 jquery:

$.ajax({
  type: 'get',
  url: 'https://www.example.com/api/test',
  xhrfields: {
    withcredentials: true
  }
});

 

使用提取 api:

fetch('https://www.example.com/api/test', {
    credentials: 'include'
});

 

服务器必须允许凭据。 若要允许跨域凭据,请调用 allowcredentials:

 

options.addpolicy("allowcredentials",
    builder =>
    {
        builder.withorigins("http://example.com")
               .allowcredentials();
    });

 

http 响应包含一个 @no__t 0 的标头,该标头通知浏览器服务器允许跨源请求的凭据。

如果浏览器发送凭据,但响应不包含有效的 @no__t 0 标头,则浏览器不会向应用程序公开响应,而且跨源请求会失败。

允许跨域凭据会带来安全风险。 另一个域中的网站可以代表用户将登录用户的凭据发送给该应用程序,而无需用户的知识。

cors 规范还指出,如果 @no__t 标头存在,则将源设置为 "*" (所有源)是无效的。

预检请求

对于某些 cors 请求,浏览器会在发出实际请求之前发送其他请求。 此请求称为预检请求。 如果满足以下条件,浏览器可以跳过预检请求:

  • 请求方法为 get、head 或 post。
  • 应用未设置 acceptaccept-languagecontent-languagecontent-type 或 @no__t 为的请求标头。
  • @no__t 的标头(如果已设置)具有以下值之一:
    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain

为客户端请求设置的请求标头上的规则适用于应用通过调用 @no__t @no__t 对象上的的标头。 cors 规范调用这些标头作者请求标头。 规则不适用于浏览器可以设置的标头,如 user-agenthost 或 content-length

下面是预检请求的示例:

options https://myservice.azurewebsites.net/api/test http/1.1
accept: */*
origin: https://myclient.azurewebsites.net
access-control-request-method: put
access-control-request-headers: accept, x-my-custom-header
accept-encoding: gzip, deflate
user-agent: mozilla/5.0 (compatible; msie 10.0; windows nt 6.2; wow64; trident/6.0)
host: myservice.azurewebsites.net
content-length: 0

预航班请求使用 http options 方法。 它包括两个特殊标头:

  • access-control-request-method:将用于实际请求的 http 方法。
  • access-control-request-headers:应用在实际请求上设置的请求标头的列表。 如前文所述,这不包含浏览器设置的标头,如 user-agent

cors 预检请求可能包括一个 @no__t 0 标头,该标头向服务器指示与实际请求一起发送的标头。

若要允许特定标头,请调用 withheaders:

 options.addpolicy("allowheaders",
    builder =>
    {
        builder.withorigins("http://example.com")
               .withheaders(headernames.contenttype, "x-custom-header");
    });

 

若要允许所有作者请求标头,请调用 allowanyheader:

 

options.addpolicy("allowallheaders",
    builder =>
    {
        builder.withorigins("http://example.com")
               .allowanyheader();
    });

 

浏览器的设置方式并不完全一致 access-control-request-headers。 如果将标头设置为 @no__t 0 (或使用 allowanyheader)以外的任何内容,则至少应包含 acceptcontent-type 和 @no__t,以及要支持的任何自定义标头。

下面是针对预检请求的示例响应(假定服务器允许该请求):

http/1.1 200 ok
cache-control: no-cache
pragma: no-cache
content-length: 0
access-control-allow-origin: https://myclient.azurewebsites.net
access-control-allow-headers: x-my-custom-header
access-control-allow-methods: put
date: wed, 20 may 2015 06:33:22 gmt

响应包括一个 @no__t 0 标头,该标头列出了允许的方法,还可以选择一个 @no__t 标头,其中列出了允许的标头。 如果预检请求成功,则浏览器发送实际请求。

如果预检请求被拒绝,应用将返回200 ok响应,但不会向后发送 cors 标头。 因此,浏览器不会尝试跨域请求。

设置预检过期时间

@no__t 的标头指定可缓存对预检请求的响应的时间长度。 若要设置此标头,请调用 setpreflightmaxage:

options.addpolicy("setpreflightexpiration",
    builder =>
    {
        builder.withorigins("http://example.com")
               .setpreflightmaxage(timespan.fromseconds(2520));
    });

 

cors 如何工作

本部分介绍 http 消息级别的cors请求中发生的情况。

  • cors不是一种安全功能。 cors 是一种 w3c 标准,可让服务器放宽相同的源策略。
    • 例如,恶意执行组件可能会对站点使用阻止跨站点脚本(xss) ,并对启用了 cors 的站点执行跨站点请求,以窃取信息。
  • api 不能通过允许 cors 来更安全。
    • 它由客户端(浏览器)来强制执行 cors。 服务器执行请求并返回响应,这是返回错误并阻止响应的客户端。 例如,以下任何工具都将显示服务器响应:
      • fiddler
      • postman
      • .net httpclient
      • web 浏览器,方法是在地址栏中输入 url。
  • 这是一种方法,使服务器能够允许浏览器执行跨源xhr或获取 api请求,否则将被禁止。
    • 浏览器(不含 cors)不能执行跨域请求。 在 cors 之前,使用jsonp来绕过此限制。 jsonp 不使用 xhr,它使用 <script> 标记接收响应。 允许跨源加载脚本。

cors 规范介绍了几个新的 http 标头,它们启用了跨域请求。 如果浏览器支持 cors,则会自动为跨域请求设置这些标头。 若要启用 cors,无需自定义 javascript 代码。

下面是一个跨源请求的示例。 @no__t 0 标头提供发出请求的站点的域。 @no__t 的标头是必需的,并且必须与主机不同。

get https://myservice.azurewebsites.net/api/test http/1.1
referer: https://myclient.azurewebsites.net/
accept: */*
accept-language: en-us
origin: https://myclient.azurewebsites.net
accept-encoding: gzip, deflate
user-agent: mozilla/5.0 (compatible; msie 10.0; windows nt 6.2; wow64; trident/6.0)
host: myservice.azurewebsites.net

如果服务器允许该请求,则会在响应中设置 @no__t 的标头。 此标头的值可以与请求中的 @no__t 0 标头匹配,也可以是通配符值 "*",表示允许任何源:

http/1.1 200 ok
cache-control: no-cache
pragma: no-cache
content-type: text/plain; charset=utf-8
access-control-allow-origin: https://myclient.azurewebsites.net
date: wed, 20 may 2015 06:27:30 gmt
content-length: 12

test message

如果响应不包括 @no__t 的标头,则跨域请求会失败。 具体而言,浏览器不允许该请求。 即使服务器返回成功的响应,浏览器也不会将响应提供给客户端应用程序。

 

测试 cors

测试 cors:

  1. 创建 api 项目。 或者,您也可以下载该示例。
  2. 使用本文档中的方法之一启用 cors。 例如:

 

public void configure(iapplicationbuilder app, ihostingenvironment env)
{
    if (env.isdevelopment())
    {
        app.usedeveloperexceptionpage();
    }
    else
    {
        app.usehsts();
    }

    // shows usecors with corspolicybuilder.
    app.usecors(builder =>
    {
        builder.withorigins("http://example.com",
                            "http://www.contoso.com",
                            "https://localhost:44375",
                            "https://localhost:5001");
    });

    app.usehttpsredirection();
    app.usemvc();
}

 

 警告

withorigins("https://localhost:<port>"); 应仅用于测试类似于下载示例代码的示例应用。

  1. 创建 web 应用项目(razor pages 或 mvc)。 该示例使用 razor pages。 可以在与 api 项目相同的解决方案中创建 web 应用。
  2. 将以下突出显示的代码添加到索引 cshtml文件中:

 

@page
@model indexmodel
@{
    viewdata["title"] = "home page";
}

<div class="text-center">
    <h1 class="display-4">cors test</h1>
</div>

<div>
    <input type="button" value="test" 
           onclick="requestval('https://<web app>.azurewebsites.net/api/values')" />
    <span id='result'></span>
</div>

<script>
    function requestval(uri) {
        const resultspan = document.getelementbyid('result');

        fetch(uri)
            .then(response => response.json())
            .then(data => resultspan.innertext = data)
            .catch(error => resultspan.innertext = 'see f12 console for error');
    }
</script>

  1. 在上面的代码中,将 url: 'https://<web app>.azurewebsites.net/api/values/1', 替换为已部署应用的 url。

  2. 部署 api 项目。 例如,部署到 azure。

  3. 从桌面运行 razor pages 或 mvc 应用,然后单击 "测试" 按钮。 使用 f12 工具查看错误消息。

  4. 从 @no__t 中删除 localhost 源,并部署应用。 或者,使用其他端口运行客户端应用。 例如,在 visual studio 中运行。

  5. 与客户端应用程序进行测试。 cors 故障返回一个错误,但错误消息不能用于 javascript。 使用 f12 工具中的 "控制台" 选项卡查看错误。 根据浏览器,你会收到类似于以下内容的错误(在 f12 工具控制台中):

    • 使用 microsoft edge:

      sec7120: [cors] 源 https://localhost:44375 在 @no__t 上找不到跨源资源的访问控制允许源响应标头中的 https://localhost:44375

    • 使用 chrome:

      对源 https://localhost:44375 https://webapi.azurewebsites.net/api/values/1 的 xmlhttprequest 的访问已被 cors 策略阻止:请求的资源上没有 "访问控制-允许" 标头。

可以使用工具(如fiddler或postman)测试启用 cors 的终结点。 使用工具时,@no__t 的标头指定的请求源必须与接收请求的主机不同。 如果请求不是基于 origin 标头的值域的,则:

  • 不需要 cors 中间件来处理请求。
  • 不会在响应中返回 cors 标头。