ASP.NET Core 启用CORS

浏览器的安全阻止一个域的本地页面请求另外不同域的本地页面,这个限制叫同源策略,这个安全特性用来阻止恶意站点从别的网站读取数据

例如假如我有一个页面叫A.html 

https://foo.example/A.html

现在页面A.html有一个ajax代码尝试读取B.html的HTML的源代码,B页面位于

https://bar.other

B.html位于不同的域,由于同源策略限制,A.html不能做ajax请求,ajax调用将返回错误消息:

No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

W3C提供了标准来放宽同源策略,允许实现跨源资源共享(CORS),如果https://bar.other实现CORS https://foo.example/A.html能够ajax请求并读取B.html

1 CORS如何工作

站点一旦启用了CORS,Access-Control-Allow-Origin会被添加到请求的头部,请求头部将被自动设置跨域请求

因此,当一个页请求到另外一个服务器或者域名的资源,服务器的响应Access-Control-Allow-Origin值被设置

通常,这个值为*,这意味着服务器共享请求资源针对互联网上的每个域名,有时候,这个header的值将被设置为特定域名(或者域名列表),这意味着服务将共享资源仅仅针对特定域名(域列表)。

2 在ASP.NET Core中启用CORS

在启动项中添加如下代码:

builder.Services.AddCors();

注意我们添加代码行使用可选AllowAnyOrigin允许每一个域能够CORS请求:

app.UseCors(builder =>
{
    builder.AllowAnyOrigin()
           .AllowAnyMethod()
           .AllowAnyHeader();
});

下面描述了各个方法作用

AllowAnyMethod() – 允许所有HTTP方法

AllowAnyHeader() – 允许所有请求头

AllowCredentials() – 服务器必须允许凭据

如果只针对特定的域名启用CORS,像http://www.domain.com , 在这种场景下你需要修改代码如下:

app.UseCors(builder =>
{
    builder.WithOrigins("http://www.domain.com")
           .AllowAnyOrigin()
           .AllowAnyMethod()
           .AllowAnyHeader();
});

你也可以指定多个域在下面:

app.UseCors(builder =>
{
    builder.WithOrigins(new string[] { "https://example1.com", "https://example2.com" })
           .AllowAnyOrigin()
           .AllowAnyMethod()
           .AllowAnyHeader();
});

3 在action或者controller上应用CORS策略

我们能定义一个或者多个CORS策略,针对策略添加CORS规则,我们将这些CORS规则应用到Controller和Action方法

下面代码定义了用户CORS策略命名为MyPolicy

var builder = WebApplication.CreateBuilder(args);
// Adding CORS Policy
builder.Services.AddCors(options =>
{
    options.AddPolicy("MyPolicy",
        builder => builder.WithOrigins("https://www.yogihosting.com"));
});
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
// Shows UseCors with named policy.
app.UseCors("MyPolicy");
app.UseAuthorization();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

将策略名字传递到UseCors()方法:现在将CORS策略应用到每个action或者controller

3.1 每个Action

指定CORS策略针对特定的action,在action上添加[EnableCors]特性并指定策略名称:

[EnableCors("MyPolicy")]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

3.2 每个Controller

[EnableCors("MyPolicy")]
public class HomeController : Controller

在Controller和action上禁用CORS,使用[DisableCors]特性:

[DisableCors]
public string Get(int id)
{
    return "value";
}

源代码地址:

https://github.com/bingbing-gui/Asp.Net-Core-Skill/tree/master/Fundamentals/AspNetCore.GlobalizationLocalization/AspNetCore.GlobalLocalResFiles

参考文献

https://www.yogihosting.com/aspnet-core-enable-cors/

https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-7.0#enable-cors

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值