2

hi i have tried different ways to enable cors but failed my code is.am using spa app for presenting data but couldn't pass cors.browser shows the error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/Values. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

 public void ConfigureServices(IServiceCollection services)
    {
       services.AddControllers().AddNewtonsoftJson(opt =>
        {
            opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        });
        services.AddCors();
        services.AddSignalR();
        services.AddControllersWithViews();
        services.AddDbContext<DataContext>(x =>
        {
            x.UseLazyLoadingProxies();
            x.UseMySql(Configuration.GetConnectionString("DefaultConnection"));
        });
        IdentityBuilder builder = services.AddIdentityCore<User>(opt =>
        {opt.User.RequireUniqueEmail = true;            
        }).AddRoles<IdentityRole>();
        builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
        builder.AddEntityFrameworkStores<DataContext>();
        builder.AddSignInManager<SignInManager<User>>();
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
                        .GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
                    ValidateIssuer = false,
                    ValidateAudience = false

                };
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];
                        if (string.IsNullOrEmpty(accessToken) == false)
                        {
                            context.Token = accessToken;
                        }
                        return Task.CompletedTask;
                    }
                };
            });
        services.AddAuthorization(options =>
        {
            options.AddPolicy(constant.RequireVisionTrackAdminRole, policy => policy.RequireRole(constant.VisionTrackAdmin));
            options.AddPolicy(constant.RequireAdminRole, policy => policy.RequireRole(constant.Admin, constant.VisionTrackAdmin));
        });
        services.AddScoped<IAuthRepository, AuthRepository>();
        services.AddAutoMapper(typeof(VisionTrackRepository).Assembly);
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/build";
        });
    }

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }       
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseSpaStaticFiles();          
        app.UseRouting();
        app.UseCors(
            options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
        );
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<VisionTrackHub>("/VisionTrack").RequireCors("CorsPolicy");
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action=Index}/{id?}").RequireCors("CorsPolicy");

        });
        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "ClientApp";

            if (env.IsDevelopment())
            {
                spa.UseReactDevelopmentServer(npmScript: "start");
            }
        });

    }

also tried this guide not working [https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1] Is it because of authorization middle ware or is something to be done on endpoints?

4 Answers 4

3

I think that's related to fact, that you cannot use both options.AllowAnyOrigin() and authentication middleware. In your case you are obliged to explicitly define allowed origins.

If you defined your CORS in a way given below, the request block should not happen.

services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
    builder
        .WithOrigins(new[]{"http://YOUR_FRONTEND_ORIGIN"})
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials();
}));
app.UseCors("CorsPolicy");
Sign up to request clarification or add additional context in comments.

1 Comment

What for local? I.e. I'd use "example.com" as the origin paired with AllowCredentials, but how do I also AllowAnyOrigin for when I'm running on my dev machine?
2

In your Startup file you have two main method, ConfigureServices, and Configure method.

In you ConfigureServices method define it as below:

 services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader());
        });

And in Configure method add this line:

app.UseCors("CorsPolicy");

Note: app.UseCors("CorsPolicy") should be after app.UseRouting() and before app.UserAuthentication()

Comments

1

I resolved comment line //app.UseHttpsRedirection();

        //app.UseHttpsRedirection();           

        app.UseRouting();


        // global cors policy
        app.UseCors();


        app.UseAuthorization();

Comments

0

This solution solved my case:

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.AddControllers();
        services.AddCors();
    }

    // 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.UseRouting();

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

        app.UseAuthorization();

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

https://github.com/dotnet/aspnetcore/issues/16672

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.