menendeze
menendeze

Reputation: 1

ASP.NET Core Web API - Blazor WASM - CORS error after some time

I have an ASP.NET Core 8 Web API and Blazor Wasm on .NET 8, JWT

In the API the program looks like this.

builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(policy =>{policy.AllowAnyMethod().AllowAnyHeader().SetIsOriginAllowed(origin => true).AllowCredentials();});
});

...

var app = builder.Build();

...

app.UseCors();

I deployed and everything works fine. After almost a week I started receiving this error:

Access to fetch at 'https://backend.net/api/packages/fullpackage' from origin 'https://frontend.com' 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.

When I look at the preflight, I get this.

access-control-allow-credentials: true access-control-allow-headers: authorization,content-type access-control-allow-methods: POST

And the request gets this.

URL: https://backend.net/api/packages/fullpackage Method: POST Code: 500 Internal Server Error Directive: strict-origin-when-cross-origin

It happens once, but I really need that online, after looking everywhere I tried switching from the API host and it worked again. That was like a week ago, now I have the same problem.

I already tried these things:

I've seen a lot of QA here and different ways to do it.

Is there something I'm missing?

Also the first time that worked used this:

app.UseCors(x => x
       .AllowAnyMethod()
       .AllowAnyHeader()
       .SetIsOriginAllowed(origin => true)
       .AllowCredentials());

Then I switched to the builder like I said at the beginning, but didn't work until I switched host and url.

Thank you in advance

Edit, this is the full code:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Text;
using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.


builder.Services.AddControllers().AddJsonOptions(x => x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "TSystem API", Version = "v1" });
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = @"JWT Authorization header using the Bearer scheme. <br /> <br />
                      Enter 'Bearer' [space] and then your token in the text input below.<br /> <br />
                      Example: 'Bearer 12345abcdef'<br /> <br />",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer"
    });
    c.AddSecurityRequirement(new OpenApiSecurityRequirement()
      {
        {
          new OpenApiSecurityScheme
          {
            Reference = new OpenApiReference
              {
                Type = ReferenceType.SecurityScheme,
                Id = "Bearer"
              },
              Scheme = "oauth2",
              Name = "Bearer",
              In = ParameterLocation.Header,
            },
            new List<string>()
          }
        });
});

Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("MYLIC");

var isDev = builder.Environment.IsDevelopment;

if (isDev.Invoke())
{
    //LocalConnection
    builder.Services.AddDbContext<DataContext>(x => x.UseSqlServer("name=LocalConnection"));
}
else
{
    //CloudConnection
    builder.Services.AddDbContext<DataContext>(x => x.UseSqlServer("name=CloudConnection"));
}


builder.Services.AddTransient<SeedDb>();

builder.Services.AddScoped<IApiService, ApiService>();
builder.Services.AddScoped<IFileStorage, FileStorage>();
builder.Services.AddScoped<IMailHelper, MailHelper>();


builder.Services.AddIdentity<User, IdentityRole>(x =>
{
    x.Tokens.AuthenticatorTokenProvider = TokenOptions.DefaultAuthenticatorProvider;
    x.SignIn.RequireConfirmedEmail = true;
    x.User.RequireUniqueEmail = true;
    x.Password.RequireDigit = false;
    x.Password.RequiredUniqueChars = 0;
    x.Password.RequireLowercase = false;
    x.Password.RequireNonAlphanumeric = false;
    x.Password.RequireUppercase = false;
    x.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
    x.Lockout.MaxFailedAccessAttempts = 3;
    x.Lockout.AllowedForNewUsers = true;
})
    .AddEntityFrameworkStores<DataContext>()
    .AddDefaultTokenProviders();

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(x => x.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = false,
        ValidateAudience = false,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["jwtKey"]!)),
        ClockSkew = TimeSpan.Zero
    });


builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(policy => { policy.AllowAnyMethod().AllowAnyHeader().SetIsOriginAllowed(origin => true).AllowCredentials(); });
});

//This tried calling it from the controller
builder.Services.AddCors(options =>
{
    options.AddPolicy(name: "DefaultCorsPolicy", policy => { policy.AllowAnyMethod().AllowAnyHeader().SetIsOriginAllowed(origin => true).AllowCredentials(); });
});


var app = builder.Build();
SeedData(app);

void SeedData(WebApplication app)
{
    IServiceScopeFactory? scopedFactory = app.Services.GetService<IServiceScopeFactory>();

    using (IServiceScope? scope = scopedFactory!.CreateScope())
    {
        SeedDb? service = scope.ServiceProvider.GetService<SeedDb>();
        service!.SeedAsync().Wait();
    }
}



app.UseCors();


//app.UseCors(x => x
//.AllowAnyMethod()
//.AllowAnyHeader()
//.SetIsOriginAllowed(origin => true)
//.AllowCredentials());


//app.UseCors(x => x
//       .AllowAnyMethod()
//       .AllowAnyHeader()
//       .WithOrigins("https://frontend.com")  //changed the original name
//       .AllowCredentials());





// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Upvotes: 0

Views: 147

Answers (1)

daandsp
daandsp

Reputation: 160

You should set the allowed origins of a request in the AddCors() call.

builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(policy => policy
        .AllowAnyMethod()
        .AllowAnyHeader()
        .WithOrigins("https://frontend.com")
        .AllowCredentials()
    );
});

Be sure to call the AddCors() before configuring anything like controllers or mvc.

Then call the UseCors() method.

app.UseCors();

You can read more on enabling Cross-Origin requests in ASP.NET Core in the documentation.

Hope this helps

Upvotes: 0

Related Questions