如何使用基于声明的授权保护ASP.NET Core 2.1中的静态文件夹

时间:2018-10-23 20:40:06

标签: c# asp.net-core middleware asp.net-core-2.1

我有一个使用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);
    }
}

Startup.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 = "aaa@gmail.com",
                FullName = "aaa"
            };
        }
        else
        {
            return null;
        }
    }

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

1 个答案:

答案 0 :(得分:4)

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

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

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

有关启动的更多信息。请在此处配置订单

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