Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to protect static folder in asp.net core 2.1 using claims-based authorization

I have a small project which uses asp.net core 2.1. I wish to protect folder full of static assets. I tried to implement is based on this article https://odetocode.com/blogs/scott/archive/2015/10/06/authorization-policies-and-middleware-in-asp-net-5.aspx

I am using cookies and claims-based authorization. All view which are supposed to check authorization work fine... except static folder. When I check httpContext.User it is missing all expected claims.

Middleware:

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();
    }
}

Login is very simple. Just set the cookie, when authenticate

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;
        }
    }

Once again. It works for all pages which require authentication except static folder. What am I doing wrong?

like image 881
Alexey Korsakov Avatar asked Jan 27 '23 06:01

Alexey Korsakov


1 Answers

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

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

Calling UseStaticFiles() first will short-cut the pipeline for static files. So no authentication are done on the static files.

More info on Startup.Configure order here:

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

like image 76
Marcel Avatar answered Feb 08 '23 15:02

Marcel