【问题标题】:Asp.net Core 2.2, Middleware doesn't always execute when moving between static html filesAsp.net Core 2.2,在静态 html 文件之间移动时,中间件并不总是执行
【发布时间】:2019-08-08 21:44:16
【问题描述】:

我有一个 asp.net 核心 Web 应用程序,它在 wwwroot 之外有一个静态文件目录(所有 html/csv)。我创建了一个中间件来检查用户在访问这些文件之前是否经过身份验证。但是,当我在这些静态文件中从一个 html 文件转到另一个(通过 url 或 href)时,中间件有时并不总是执行。即使我注销,有时我仍然可以访问这些文件。我也在使用 Cookies 身份验证方案而不是身份。这个中间件基于 Scott Allen 的教程 https://odetocode.com/blogs/scott/archive/2015/10/06/authorization-policies-and-middleware-in-asp-net-5.aspx

我尝试在中间件代码中添加断点,我发现有时即使它是一个新请求也不会触发。

Startup.cs

   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.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity<IdentityUser>()
                .AddDefaultUI(UIFramework.Bootstrap4)
                .AddEntityFrameworkStores<ApplicationDbContext>();

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

            services.AddAuthentication( options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(options =>
            {

                    options.AccessDeniedPath = "/Home/Index";
                    options.LoginPath = "/Identity/Account/Login";
            });
            services.AddAuthorization(options =>
            {
                options.AddPolicy("Authenticated", policy => policy.RequireAuthenticatedUser());
            });

            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {


            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/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.UseAuthentication();



            app.UseProtectFolder(new ProtectFolderOptions
            {
                Path = "/StaticFiles",
                PolicyName = "Authenticated",

            });



            app.UseStaticFiles();
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                Path.Combine(Directory.GetCurrentDirectory(), "Static_Files")),
                RequestPath = "/StaticFiles"
            });
            //app.UseStaticFiles(new StaticFileOptions
            //{
            //    FileProvider = new PhysicalFileProvider(


            //        Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles")),
            //        RequestPath = "/StaticFiles"
            //});



            app.UseCookiePolicy();



            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

            });
        }

        private object RedirectResult()
        {
            throw new NotImplementedException();
        }
    }

中间件

    public class ProtectFolderOptions
    {
        public PathString Path { get; set; }
        public string PolicyName { get; set; }
    }
    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class ProtectFolderExtensions
    {
        public static IApplicationBuilder UseProtectFolder(this IApplicationBuilder builder, ProtectFolderOptions options)
        {
            return builder.UseMiddleware<ProtectFolder>(options);
        }
    }

    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    public class ProtectFolder
    {
        private readonly RequestDelegate _next;
        private readonly PathString _path;
        private readonly string _policyName;

        public ProtectFolder(RequestDelegate next,ProtectFolderOptions options)
        {
            _next = next;
            _path = options.Path;
            _policyName = options.PolicyName;
        }

        public async Task Invoke(HttpContext httpContext, IAuthorizationService authorizationService)
        {



            if (httpContext.Request.Path.StartsWithSegments(_path))
            {
                var authorized = await authorizationService.AuthorizeAsync(httpContext.User, null, _policyName);


                if (authorized.Succeeded == false)
                {
                    await httpContext.ChallengeAsync();
                    return;
                }
            }



            await _next(httpContext);
        }

除非用户已登录,否则用户应该无权访问 Static_Files 目录中的这些文件。这是可行的。但是,在我退出后,有时我仍然可以访问这些 html 文件。在我退出后,中间件有时不会触发,当我在 URL 中调用新请求或使用其内部 href 跨 html 文件移动时,我将获得对 html 文件的访问权限。

【问题讨论】:

    标签: c# asp.net-core


    【解决方案1】:

    您的静态文件可能正在浏览器中缓存,因此,一旦它们被合法访问,它们就会被缓存,并且在资源过期之前后续请求不需要转到服务器。

    您可以通过以下方式禁用文件缓存:-

    app.UseStaticFiles(new StaticFileOptions()
    {
        OnPrepareResponse = (context) =>
        {
            context.Context.Response.Headers["Cache-Control"] = "no-cache, no-store";
            context.Context.Response.Headers["Expires"] = "-1";
            context.Context.Response.Headers["Pragma"] = "no-cache";
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-26
      • 2020-08-28
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-26
      • 2021-03-14
      相关资源
      最近更新 更多