簡體   English   中英

在 ASP.Net Core 5 WebAPI 中啟用 CORS

[英]Enable CORS in ASP.Net Core 5 WebAPI

有數百萬篇與此問題相關的文章和問題,但我找不到我的代碼有什么問題。 我有StartupStartupProductionStartupDevelopment ,如下所示。 另外,我正在使用ASP.Net Core 5 ,並且根據文檔,我認為我這樣做是正確的。

僅供參考,起初,我使用AllowAnyOrigin進行開發,但我也測試.WithOrigins("http://localhost:3000")並且它工作正常。 我的后端在開發中在https://localhost:44353下運行,在生產中在https://api.example.com下運行。

public class Startup
{
    protected const string CorsPolicyName = "CorsPolicyName";

    public virtual void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers()
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Converters.Add(
                    new System.Text.Json.Serialization.JsonStringEnumConverter());
            });

        services.AddABunchOfOtherServices();
    }

    public virtual void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
        app.UseCors(CorsPolicyName);
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseMiddleware<CheckUserConfirmedMiddleware>();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute
            (
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}"
            )
            .RequireCors(CorsPolicyName);
        });
    }
}

public class StartupProduction : Startup
{
    public override void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(
                CorsPolicyName,
                policy => policy
                    .WithOrigins("https://example.com", "http://example.com")
                    //.WithOrigins(Configuration.GetValue<string>("AllowedHosts").Split(';').ToArray())
                    .AllowAnyMethod()
                    .AllowAnyHeader());
        });

        base.ConfigureServices(services);
    }

    public override void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseMiddleware(typeof(ErrorHandlingMiddleware));

        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();

        base.Configure(app, env);
    }
}

public class StartupDevelopment : Startup
{
    public override void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
            options.AddPolicy(
                CorsPolicyName,
                policy =>
                    policy
                        //.AllowAnyOrigin()
                        .WithOrigins("http://localhost:3000")
                        .AllowAnyMethod()
                        .AllowAnyHeader()
            )
        );

        base.ConfigureServices(services);

        services.AddSwaggerGen(....);
    }

    public override void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseMiddleware<DevelopmentErrorHandlingMiddleware>();

        base.Configure(app, env);

        app.UseSwagger();

        app.UseSwaggerUI(options =>
        {
            options.SwaggerEndpoint("swagger/v1/swagger.json", "API v1");
            options.RoutePrefix = string.Empty;
        });
    }
}

我還嘗試了默認策略

更新

我已在 Visual Studio 中將Environment設置為Production以對其進行調試,現在我在開發中面臨同樣的問題。

CORS 策略已阻止從源“http://localhost:3000”獲取“https://localhost:44353/api/v1/User”的訪問權限:對預檢請求的響應未通過訪問控制檢查:否'Access-Control-Allow-Origin' header 存在於請求的資源上。 如果不透明的響應滿足您的需求,請將請求的模式設置為“no-cors”以獲取禁用 CORS 的資源。

解決方法

我注意到是 IIS 阻止了請求。 它僅在我的 appsettings.json 中有"AllowedHosts": "*", appsettings.json 因此,作為一種解決方法,我在我的 appsettings.json 中添加了“ appsettings.json "MyRandomKey": "https://example.com",並在我的Startup中使用以下內容。

services.AddCors(options =>
                options.AddPolicy(
                    CorsPolicyName,
                    policy =>
                        policy
                            .WithOrigins(Configuration.GetValue<string>("MyRandomKey").Split(";").ToArray())
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                )
            );

AllowedHosts 和 CORS 是不同的。

AllowedHosts 用於主機過濾,因此即使您在應用程序中配置了 CORS 策略但不允許主機,IIS 也會拒絕該請求。

請參考此鏈接: Difference between AllowedHosts in appsettings.json and UseCors in .NET Core API 3.x

默認情況下它是 * 但您可以根據您的要求將其更改為。 在您的情況下,您可以設置“api.example.com”,或者如果您也想從 localhost 允許,那么“api.example.com;localhost”。 一旦你設置了它,那么 IIS 將開始接受來自這些域的請求。

一旦 IIS 將開始接受請求,那么您的應用程序級別配置的 CORS 策略將被應用並工作。 所以基本上 CORS 是允許訪問 WebAPI 中的資源。

我認為沒關系,而且,您可以從 DB 或 JSON 文件中獲取來源。 此外,您可以使用 ActionFilterAttribute 和這部分代碼

    var csp = "default-src 'self' http://localhost:3000; object-src 'none'; frame-ancestors 'none'; sandbox allow-forms allow-same-origin allow-scripts; base-uri 'self';";

if (!context.HttpContext.Response.Headers.ContainsKey("Content-Security-Policy"))
{
    context.HttpContext.Response.Headers.Add("Content-Security-Policy", csp);
}

if (!context.HttpContext.Response.Headers.ContainsKey("X-Content-Security-Policy"))
{
    context.HttpContext.Response.Headers.Add("X-Content-Security-Policy", csp);
}

這個關於 CORS 預檢請求的文檔中,您可以找到以下信息:

CORS 預檢請求用於確定所請求的資源是否設置為由服務器跨源共享。 並且 OPTIONS 請求始終是匿名的,如果未啟用匿名身份驗證,服務器將無法正確響應預檢請求。

CORS 策略已阻止從源“http://localhost:3000”獲取“https://localhost:44353/api/v1/User”的訪問權限:對預檢請求的響應未通過訪問控制檢查:否'Access-Control-Allow-Origin' header 存在於請求的資源上。 如果不透明的響應滿足您的需求,請將請求的模式設置為“no-cors”以獲取禁用 CORS 的資源。

要解決上述問題,如果您使用 CORS 在本地運行應用程序以進行測試,您可以嘗試啟用匿名身份驗證。

此外,如果您的應用程序托管在 IIS 上,您可以嘗試安裝IIS CORS 模塊並為應用程序配置 Z5A8ZFF0B76024BDEB3EEC9D924。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM