2
votes

Hi i have trouble with cors error i read the all examples from stack and other website but any dont helped me. I have the rest api written in net core 2.1 and the client app( i use react framework) and i try to fetch api from rest api, all was on the localhost. Server on http://localhost:44334 and react client on http://localhost:3000 When i try to fetch api on the server i get this exception:

Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information: Policy execution failed. Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information: Request header 'access-control-allow-origin' not allowed in CORS policy. Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 3.9493ms 204

But on the react client on browser i get this:

Access to fetch at 'https://localhost:44334/Account' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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 my c# class when i register cors, i remember to register instance behind .AddMvc method

 public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddAuthorization(options =>
        {
            options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Administrator"));
        });


        services.AddCors();


        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        services.AddOptions();
        services.AddMemoryCache();

        var jwt_settings = Configuration.GetSettings<JwtSettings>();

        services.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(cfg =>
            {
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt_settings.Key)),
                    ValidIssuer = jwt_settings.Issuer,
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime = true
                };
            });
        var builder = new ContainerBuilder();
        //register commandModules 
        builder.Populate(services);
        builder.RegisterModule(new ContainerModules(Configuration));
        ApplicationContainer = builder.Build();

        return new AutofacServiceProvider(ApplicationContainer);
    }

And register on Configure method:

 app.UseCors(
            options => options.WithOrigins("http://localhost:3000").AllowAnyMethod()
        );

        app.UseMvc();

And this i paste the react code where i fetch api:

export function login(password, email) {
fetch("https://localhost:44334/Account", {
    method: "POST", // *GET, POST, PUT, DELETE, etc.
    mode: "cors", // no-cors, cors, *same-origin
    cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
    credentials: "same-origin", // include, *same-origin, omit
    headers: {
        "Content-Type": "application/json",
        // "Content-Type": "application/x-www-form-urlencoded",
        'Accept': 'application/json',
        "Access-Control-Allow-Origin": "*"
    },
    body: {email, password}
}).then(res => res.json())
    .then(response => console.log('Success:', response))
    .catch(error => console.error('Error:', error));

}

And the controller method on this i dont use EnableCors:

[HttpPost]
    public async Task<IActionResult> Login([FromBody] LoginAsync login)
    {
        login.TokenId = Guid.NewGuid();
        await _commandDispatcher.DispatchAsync(login);
        var jwt = _memoryCache.Get<JsonWebToken>(login.TokenId);
        return Json(jwt);
    }
1

1 Answers

6
votes

Add below code Within Configure services method

      services.AddCors(options =>
        {
            // this defines a CORS policy called "default"
            options.AddPolicy("default", policy =>
            {
                policy.WithOrigins("http://localhost:3000")
                    .AllowAnyHeader()
                    .AllowAnyMethod();
            });
        });  

Within configure method

app.UseCors("default");