3

I created an API using ASP.NET Core 5 and a WASM Blazor as client but I get an error of

Access to fetch at 'http://localhost:26173/api/tickets' from origin 'https://localhost:44351' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

This is in my Startup class in the API

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();
    });
}

In my WASM this is how I get the list

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>();
}

What am I doing wrong?

2 Answers 2

6

You can try the following configuration:

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

and use it

app.UseCors("CorsPolicy");

Having the host set as true means that it will allow any browser access this one. To limit this, replace (host) => true with (host) => {return host == "my.domain.com";} to allow just your trusted domain.

See also: asp net core - No 'Access-Control-Allow-Origin' header is present on the requested resource.

0
2

I assume that you are using Google Chrome as your browser. Unfortunately, due to security guidelines, this can lead to the error message you mentioned. It finally worked for me when I installed this Chrome extension: https://chrome.google.com/webstore/detail/moesif-origin-cors-change/digfbfaphojjndkpccljibejjbppifbc

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.