为了账号安全,请及时绑定邮箱和手机立即绑定

.net core 2.2 和广泛开放的 CORS

.net core 2.2 和广泛开放的 CORS

C#
侃侃尔雅 2022-12-31 10:38:48
从 .net core 2.2 开始,我们不能同时接受所有来源和接受凭据。虽然它解决了安全问题,但在某些情况下我们并不关心并且希望事情完全开放。因此,我在几个线程上找到的建议解决方案是:    Services.AddCors(CorsOptions =>     {         CorsOptions.AddPolicy("AllowAll", P => { P             .SetIsOriginAllowed(_ => true)             .AllowAnyMethod()             .AllowAnyHeader()             .AllowCredentials();         });     });但这仍然会出现以下错误:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。对于具有 2.2 的广泛开放的 CORS,什么是可行的解决方案?
查看完整描述

2 回答

?
繁花如伊

TA贡献2012条经验 获得超12个赞

我认为您所需要的只是@Praneet 提到的以下内容。创建全访问策略


services

    .AddCors(options => options

        .AddPolicy("WideOpen", p => p

            .AllowAnyOrigin()

            .AllowAnyMethod()

            .AllowAnyHeader())

    );

您还需要一个Configure方法来全局启用它


public void Configure(IApplicationBuilder app, IHostingEnvironment env)

{

    app.UseCors("WideOpen");

}

更新的答案


services

    .AddCors(options => options

        .AddPolicy("WideOpen", p => p

            .SetIsOriginAllowedToAllowWildcardSubdomains()

            .WithOrigins("*")

            .AllowAnyMethod()

            .AllowAnyHeader()

            .AllowCredentials())

    );

根据允许的来源所需的文件。 SetIsOriginAllowedToAllowWildcardSubdomains所以我已经设置WithOrigins使用通配符


更新的答案 2


好的,我对你的问题有个想法。我认为这不是理想或推荐的解决方案,但它会起作用。您可以有一个中间件,它为每个请求注入响应标头,这些请求需要允许 AnyOrigin、AnyMethod 和 AnyHeader 以及凭据。但是,它只会Access-Control-Allow-Origin为请求中存在的 Origin 添加标头,因此允许任何来源。


如果 Ajax 检查不起作用,您可以将其删除。唯一的缺点是,它将为所有请求注入标头。


public class WideOpenCorsMiddleware

{

    private readonly RequestDelegate _next;


    public WideOpenCorsMiddleware(RequestDelegate next)

    {

        _next = next;

    }


    public async Task Invoke(HttpContext context)

    {

        var response = context.Response;


        // check if it's an ajax request

        if (context.Request.Headers != null && context.Request.Headers["X-Requested-With"] == "XMLHttpRequest")

        {

            response.Headers.Add("Access-Control-Allow-Origin",

                new[] { (string)context.Request.Headers["Origin"] });

            response.Headers.Add("Access-Control-Allow-Headers",

                new[] { "Origin, X-Requested-With, Content-Type, Accept" });

            response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET, POST, PUT, DELETE, OPTIONS" });

            response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });

            response.StatusCode = 200;

        }


        // if not a pre-flight request

        if (context.Request.Method != "OPTIONS")

        {

            await _next(context);

        }

    }

}

你也可以有这个扩展方法,这样你就可以很容易地在Configure方法中使用它。


// Extension method used to add the middleware to the HTTP request pipeline.

public static class MiddlewareExtensions

{

    public static IApplicationBuilder UseWideOpenCors(this IApplicationBuilder builder)

    {

        return builder.UseMiddleware<WideOpenCorsMiddleware>();

    }

}

最后,在Configure方法中,添加以下行,可能在顶部:


public void Configure(IApplicationBuilder app, IHostingEnvironment env)

{

    app.UseWideOpenCors();

}


查看完整回答
反对 回复 2022-12-31
?
jeck猫

TA贡献1909条经验 获得超7个赞

在您的 appsettings.json 中添加您的 cors 来源。是这样的:


"CorsOrigins": {

    "Urls": [ "http://localhost:4200", "http://localhost:8090", "https://localhost:44376" ]

  }

然后像这样设置你的启动:


var corsOriginsSection = Configuration.GetSection("CorsOrigins");

var origins = corsOriginsSection.Get<CorsOrigins>();


services.AddCors(options => options.AddPolicy("AllowSpecificOrigin", p => p.WithOrigins(origins.Urls)

                                               .AllowAnyMethod()

                                               .AllowAnyHeader()));

然后在你的控制器上添加这个:


 [EnableCors("AllowSpecificOrigin")]

那应该有效。


我将使用的类是这样的:


public interface ICorsOrigins

{

    string[] Urls { get; set; }

}

public class CorsOrigins : ICorsOrigins

{

    public string[] Urls { get; set; }

}

我会保留 appsettings 中的起源,否则它将是硬编码的东西。


就像特定来源一样,创建一个策略 All Access 并根据您的要求使用它


查看完整回答
反对 回复 2022-12-31
  • 2 回答
  • 0 关注
  • 80 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信