簡體   English   中英

.net core 3.1 c# cors 不適用於 angular 7

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

嗨,我嘗試了不同的方法來啟用 cors,但我的代碼失敗了。我使用 spa 應用程序來呈現數據,但無法通過 cors.browser 顯示錯誤跨源請求已阻止:同源策略不允許在http讀取遠程資源://localhost:5000/Values (原因:缺少 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");
            }
        });

    }

也試過這個指南不起作用 [ https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1]是因為授權中間件還是要在端點上做些什么?

我認為這與事實有關, 您不能同時使用options.AllowAnyOrigin()和身份驗證中間件。 在您的情況下,您有義務明確定義允許的來源。

如果您以下面給出的方式定義了 CORS,則不應發生請求塊。

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

在您的Startup文件中,您有兩個主要方法, ConfigureServicesConfigure方法。

在您的ConfigureServices方法中將其定義如下:

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

Configure方法中添加這一行:

app.UseCors("CorsPolicy");

注意: app.UseCors("CorsPolicy")應該在app.UseRouting()app.UserAuthentication()之前

我解決了注釋行 //app.UseHttpsRedirection();

        //app.UseHttpsRedirection();           

        app.UseRouting();


        // global cors policy
        app.UseCors();


        app.UseAuthorization();

這個解決方案解決了我的情況:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM