Getting CORS policy preflight request headers error when calling API Endpoint of ASP.net Core...

Discussão em 'Angular' iniciado por Dennis Bahl, Dezembro 6, 2024.

  1. Dennis Bahl

    Dennis Bahl Guest

    i'm reading stackoverflow posts now for many years and they always helped me lot solving my problems. Thank you all a lot for that. Now i couldn't find a helpful answer to my question so that was a good opportunity to register :)

    My Question: I have a ASP.net Core WebApi to authorize and authenticate users (.net 7). I'm running into a CORS problem when calling the login endpoint of that API using my Angular App: Access to fetch at 'https://myAPI.azurewebsites.net/accounts/authenticate' from origin 'https://myAPP.azurewebsites.net' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

    When i call the endpoint with Postman everything is fine and i'm getting the response as expected. My Login method in the frontend is simply:

    login(email: string, password: string) {
    return this.http.post<any>(`${baseUrl}/authenticate`, { email, password }, { withCredentials: true })
    .pipe(map(account => {
    this.accountSubject.next(account);
    this.startRefreshTokenTimer();
    return account;
    }));
    }


    The Program.cs looks like following:

    var builder = WebApplication.CreateBuilder(args);

    // add services to DI container
    {
    var services = builder.Services;
    var env = builder.Environment;

    services.AddDbContext<DataContext>();
    services.AddCors();
    services.AddControllers().AddJsonOptions(x =>
    {
    // serialize enums as strings in api responses (e.g. Role)
    x.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
    });

    services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
    services.AddSwaggerGen();

    // configure strongly typed settings object
    services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));

    // configure DI for application services
    services.AddScoped<IJwtUtils, JwtUtils>();
    services.AddScoped<IAccountService, AccountService>();
    services.AddScoped<IMailService, EmailService>();
    builder.Services.Configure<MailSettings(builder.Configuration.GetSection(nameof(MailSettings)));

    }

    var app = builder.Build();

    // migrate any database changes on startup (includes initial db creation)
    using (var scope = app.Services.CreateScope())
    {
    var dataContext = scope.ServiceProvider.GetRequiredService<DataContext>();
    dataContext.Database.Migrate();
    }

    app.UseHttpsRedirection();

    app.UseSwagger();
    app.UseSwaggerUI(x => x.SwaggerEndpoint("/swagger/v1/swagger.json", ".NET Sign-up and Verification API"));

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

    // global error handler
    app.UseMiddleware<ErrorHandlerMiddleware>();

    // custom jwt auth middleware
    app.UseMiddleware<JwtMiddleware>();

    app.MapControllers();

    app.Run(builder.Configuration["AppSettings:eek:rigins"]);


    That results is the CORS policy error message as seen above. I also tried to set up my own custom CORS Policy:

    .
    .
    .
    // global cors policy
    app.UseCors(
    policy =>
    {
    policy.WithOrigins
    ("http://localhost:8100",
    "https://myAPP.azurewebsites.net",
    "https://API1.azurewebsites.net",
    "https://API2.azurewebsites.net",
    "https://www.myDomain.de")
    .SetIsOriginAllowedToAllowWildcardSubdomains()
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials()
    .WithMethods("GET", "PUT", "POST", "DELETE", "OPTIONS");
    }
    );
    .
    .
    .


    The results are the same. I played a bit around with the different settings and read a lot here on stackoverflow but i feel a bit stuck, so every help is very much apreciated :)

    See in Description above.

    Continue reading...

Compartilhe esta Página