【问题标题】:what should be the order of the code .net core?代码.net核心的顺序应该是什么?
【发布时间】:2021-10-27 22:39:11
【问题描述】:

url 在任何进程都返回登录路径,我认为ConfigureServices 中的代码顺序错误我该如何解决?

  public void ConfigureServices(IServiceCollection services)
        {
            services.AddDI();//custom Startup Collection
            services.AddDbContext<AppDbContext>();
            services.AddIdentity<AppUser, AppRole>(options =>
            {

                options.SignIn.RequireConfirmedEmail = true;
                options.User.RequireUniqueEmail = true;

            }).AddErrorDescriber<CustomIdentityValidator.CustomIdentityValidator>().AddEntityFrameworkStores<AppDbContext>()
            .AddDefaultTokenProviders();
        
            services.AddAutoMapper(typeof(Startup));//
            services.AddControllersWithViews();
   
            
            services.AddAuthentication();
            services.AddRazorPages();
            services.Configure<DataProtectionTokenProviderOptions>(options => options.TokenLifespan = TimeSpan.FromHours(5));
            services.Configure<EmailOptions>(Configuration);//appsettingstekileri değiştirecek
            services.AddCors(opt =>
            {
                opt.AddPolicy("global", cors =>
                {
                    cors.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
                });
            });
            services.ConfigureApplicationCookie(options =>
            {

                options.Cookie.Name = "test";
                options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict;
                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan = TimeSpan.FromDays(20);
                options.Cookie.SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.SameAsRequest;
                options.LoginPath = "/Home/SignIn";
                options.AccessDeniedPath = "/Home/AccessDenied";
            });
        }


配置:

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserManager<AppUser> userManager, RoleManager<AppRole> roleManager, IWebSiteBussRepository webSiteBussRepository)
        {


            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }


            IdentityInitializer.SeedData(userManager, roleManager).Wait();
            IdentityInitializer.StaticPage(webSiteBussRepository).Wait();

            app.UseStatusCodePagesWithReExecute("/Home/StatusCode", "?code={0}"); //en üstte olmalı 404 page 'i için yazdım
            app.UseStaticFiles();
            app.UseRouting();
            //app.UseIdentityServer();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseCors("global");

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllerRoute(
                     name: "areas",
                     pattern: "{area}/{controller=Home}/{action=Index}/{id?}"
                     );
                endpoints.MapControllerRoute(
                   name: "default",
                   pattern: "{controller=Home}/{action=Index}/{id?}"
                   );
            }); 
        }

【问题讨论】:

  • 你确定你已经登录并在端点上放了一些合适的授权吗?如果是这样...我们是否可以看到您的 Configure 方法(ConfigureServices 注册东西,Configure 使用它们来构建管道)
  • @GordonKhanhNg。我在下面发布了Configure
  • 您可以检查Asp.net Core Middleware orderUseCorsUseAuthenticationUseAuthorization必须按显示的顺序出现:对UseCors的调用必须放在UseRouting之后,但在UseAuthorizationlike this 之前。尝试改变它。

标签: c# asp.net-core .net-core asp.net-core-mvc


【解决方案1】:

甜...我可能在这里发现了你的问题...

注意,在后台app.UseIdentityServer();使用IdentityServerMiddleware(这是Identity Server的特定中间件),并使用上面的app.UseIdentityServer();,代码可以在here找到,而这个是什么that line execute

简而言之,身份服务器将身份验证过程留给AuthenticationMiddleware,由app.UseAuthentication();注册,稍后他们将处理额外的逻辑。

所以,管道顺序应该是

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseIdentityServer();
app.UseCors("global");

// or just this to be compact:
app.UseRouting();
app.UseIdentityServer();
app.UseAuthorization();
app.UseCors("global");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-30
    • 2018-08-22
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    相关资源
    最近更新 更多