简体   繁体   English

.net core 3.1 c# cors 不适用于 angular 7

[英].net core 3.1 c# cors not working with angular 7

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 .嗨,我尝试了不同的方法来启用 cors,但我的代码失败了。我使用 spa 应用程序来呈现数据,但无法通过 cors.browser 显示错误跨源请求已阻止:同源策略不允许在http读取远程资源://localhost:5000/Values (Reason: CORS header 'Access-Control-Allow-Origin' missing). (原因:缺少 CORS 标头“Access-Control-Allow-Origin”)。

 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://docs.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?也试过这个指南不起作用 [ https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1]是因为授权中间件还是要在端点上做些什么?

I think that's related to fact, that you cannot use both options.AllowAnyOrigin() and authentication middleware.我认为这与事实有关, 您不能同时使用options.AllowAnyOrigin()和身份验证中间件。 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.如果您以下面给出的方式定义了 CORS,则不应发生请求块。

services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
    builder
        .WithOrigins(new[]{"http://YOUR_FRONTEND_ORIGIN"})
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials();
}));
app.UseCors("CorsPolicy");

In your Startup file you have two main method, ConfigureServices , and Configure method.在您的Startup文件中,您有两个主要方法, ConfigureServicesConfigure方法。

In you ConfigureServices method define it as below:在您的ConfigureServices方法中将其定义如下:

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

And in Configure method add this line:Configure方法中添加这一行:

app.UseCors("CorsPolicy");

Note: app.UseCors("CorsPolicy") should be after app.UseRouting() and before app.UserAuthentication()注意: app.UseCors("CorsPolicy")应该在app.UseRouting()app.UserAuthentication()之前

I resolved comment line //app.UseHttpsRedirection();我解决了注释行 //app.UseHttpsRedirection();

        //app.UseHttpsRedirection();           

        app.UseRouting();


        // global cors policy
        app.UseCors();


        app.UseAuthorization();

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 https://github.com/dotnet/aspnetcore/issues/16672

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM