0

NetCore 3.0 and Angular the both are running on my LOCALHOST, its an Authentication project and i setup my Startup like:

 public class Startup
{

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(opt => {
            opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,

                ValidIssuer = "https://localhost:44361",
                ValidAudience = "https://localhost:4200",
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345"))
            };
        });

        services.AddCors(options =>
        {
            options.AddPolicy("EnableCORS", builder =>
            {
                builder.WithOrigins("http://localhost:4200")
                .AllowAnyHeader()
                .AllowAnyMethod();
            });
        });

        services.AddControllers();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();
        app.UseCors("EnableCORS");

        app.UseRouting();

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

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

My Angular is running on port localhost:4200 and my API runs on localhost:44361

any idea why I get that error?its very strange seems everything is fine should not be that complicated,or im missing something?its 3 days im working on it still no success

mortezasol
  • 851
  • 4
  • 14

1 Answers1

0

With endpoint routing, the CORS middleware must be configured to execute between the calls to UseRouting and UseEndpoints.

You can read this in the Enable Cross-Origin Requests documentation on Microsoft docs.

Move your app.UseCors() so it sits somewhere in between of the routing and endpoint middleware.

        app.UseRouting();
        app.UseCors("EnableCORS");

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

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
Dennis1679
  • 2,232
  • 1
  • 9
  • 32