【问题标题】:Error on CORS policy using ASP.NET Core 5 and Blazor使用 ASP.NET Core 5 和 Blazor 的 CORS 策略出错
【发布时间】:2021-09-15 21:10:29
【问题描述】:

我使用 ASP.NET Core 5 和 WASM Blazor 作为客户端创建了一个 API,但我收到了一个错误

CORS 策略已阻止从源“https://localhost:44351”获取“http://localhost:26173/api/tickets”的访问权限:没有“Access-Control-Allow-Origin”标头出现在请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

这是我在 API 中的 Startup 类

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<AppDbContext>(options => 
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddAuthentication(opt => {
        opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = false,
            ValidateAudience = false,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,

            ValidIssuer = "https://localhost:44351/",
            ValidAudience = "https://localhost:44351/",
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"]))
        };
    });

    services.AddApiService(Configuration);

    services.AddCors(policy =>
    {
        policy.AddPolicy(name: "ApplicationCors",
                            builder =>
                            {
                                builder
                                  .AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader();
                            });
    });

    services.AddControllers();
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "HelpDesk.Api", Version = "v1" });
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "HelpDesk.Api v1"));
    }

    app.UseHttpsRedirection();
    app.UseRouting();

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

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

在我的 WASM 中,这是我获取列表的方式

protected async override Task OnInitializedAsync()
{
    TicketHeaders = (await TicketService.GetTickets()).ToList();
}

TicketService.cs

public async Task<IEnumerable<TicketHeader>> GetTickets()
{
    return await httpService.Get<TicketHeader[]>("api/tickets");
}

HttpService

public async Task<T> Get<T>(string uri)
{
    var request = new HttpRequestMessage(HttpMethod.Get, uri);
    return await SendRequest<T>(request);
}

private async Task<T> SendRequest<T>(HttpRequestMessage request)
{
    // add jwt auth header if user is logged in and request is to the api url
    var user = await localStorageService.GetItem<ApplicationUserModel>("user");
    var isApiUrl = !request.RequestUri.IsAbsoluteUri;

    if (user != null && isApiUrl)
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", user.Token);

    using var response = await httpClient.SendAsync(request);

    // auto logout on 401 response
    if (response.StatusCode == HttpStatusCode.Unauthorized)
    {
        navigationManager.NavigateTo("login", true);
        return default;
    }

    // throw exception on error response
    if (!response.IsSuccessStatusCode)
    {
        var error = await response.Content.ReadFromJsonAsync<Dictionary<string, string>>();
        throw new Exception(error["message"]);
    }

    return await response.Content.ReadFromJsonAsync<T>();
}

我做错了什么?

【问题讨论】:

    标签: asp.net-core blazor


    【解决方案1】:

    你可以试试下面的配置:

     services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder
                        .AllowAnyMethod()
                        .AllowCredentials()
                        .SetIsOriginAllowed((host) => true)
                        .AllowAnyHeader());
            });
    

    并使用它

    app.UseCors("CorsPolicy");
    

    将主机设置为 true 意味着它将允许任何浏览器访问该主机。为了限制这一点,请将 (host) => true 替换为 (host) => {return host == "my.domain.com";} 以仅允许您信任的域。

    另请参阅:asp net core - No 'Access-Control-Allow-Origin' header is present on the requested resource

    【讨论】:

      【解决方案2】:

      我假设您使用 Google Chrome 作为浏览器。不幸的是,由于安全准则,这可能会导致您提到的错误消息。 当我安装这个 Chrome 扩展时,它终于对我有用了: https://chrome.google.com/webstore/detail/moesif-origin-cors-change/digfbfaphojjndkpccljibejjbppifbc

      【讨论】:

        猜你喜欢
        • 2020-07-09
        • 2019-07-15
        • 2020-07-26
        • 2020-11-02
        • 2021-07-20
        • 2021-07-09
        • 2020-04-06
        • 2017-10-14
        • 2019-11-30
        相关资源
        最近更新 更多