如何使用基于声明的授权保护asp.net core 2.1中的静态文件夹

2023-12-03

我有一个使用 asp.net core 2.1 的小项目。我希望保护充满静态资产的文件夹。我尝试实现的是基于这篇文章https://odetocode.com/blogs/scott/archive/2015/10/06/authorization-policies-and-middleware-in-asp-net-5.aspx

我正在使用 cookie 和基于声明的授权。所有应该检查授权的视图都工作正常......除了静态文件夹。当我检查 httpContext.User 时,它缺少所有预期的声明。

中间件:

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)
            {
                await httpContext.ChallengeAsync();
                return;
            }
        }

        await _next(httpContext);
    }
}

启动.cs

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddMvc()
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.AuthorizePage("/Contact");
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
        services.AddAuthorization(options =>
        {
            options.AddPolicy("Authenticated", policy => policy.RequireAuthenticatedUser());
        });

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

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseCookiePolicy();
        app.UseProtectFolder(new ProtectFolderOptions
        {
            Path = "/Docs",
            PolicyName = "Authenticated"
        });
        app.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "Docs")),
            RequestPath = "/Docs",
        });

        app.UseAuthentication();
        app.UseMvc();
    }
}

登录非常简单。认证时只需设置cookie

public async Task<IActionResult> OnGetAsync(string returnUrl = null)
    {
        ReturnUrl = returnUrl;

        if (ModelState.IsValid)
        {
            var user = await AuthenticateUser("aaa");

            if (user == null)
            {
                ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return Page();
            }

            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, user.Email),
                new Claim("FullName", user.FullName),
                new Claim(ClaimTypes.Role, "Administrator"),
            };

            var claimsIdentity = new ClaimsIdentity(
                claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var authProperties = new AuthenticationProperties
            {
            };

            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme, 
                new ClaimsPrincipal(claimsIdentity), 
                authProperties);

            _logger.LogInformation($"User {user.Email} logged in at {DateTime.UtcNow}.");

            return LocalRedirect(Url.GetLocalUrl(returnUrl));
        }
        return Page();
    }

    private async Task<ApplicationUser> AuthenticateUser(string token)
    {
        await Task.Delay(500);

        if (token == "aaa")
        {
            return new ApplicationUser()
            {
                Email = "[email protected]",
                FullName = "aaa"
            };
        }
        else
        {
            return null;
        }
    }

再次。它适用于除静态文件夹之外的所有需要​​身份验证的页面。我究竟做错了什么?


    app.UseAuthentication(); //<-- this should go first

    app.UseProtectFolder(new ProtectFolderOptions
    {
        Path = "/Docs",
        PolicyName = "Authenticated"
    });

首先调用 UseStaticFiles() 将缩短静态文件的管道。因此不对静态文件进行身份验证。

有关 Startup.Configure 订单的更多信息请参见此处:

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-2.1#order

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用基于声明的授权保护asp.net core 2.1中的静态文件夹 的相关文章

随机推荐