Home > Net >  ASP.NET Core Web API - Protect some static files with authentication
ASP.NET Core Web API - Protect some static files with authentication

Time:08-18

In my ASP.NET Core 6 Web API, I have a folder named files. And I only want to protect folder files/users with authentication.

enter image description here

In my program.cs I have this:

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(Path.Combine(builder.Environment.ContentRootPath, "files")),
    RequestPath = "/files",
});

If I put this on my program.cs all folders are "included".

builder.Services.AddAuthorization(options =>
{
    options.FallbackPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
});

Someone can help me to only protect this folder?

CodePudding user response:

you can use OnPrepareResponse as like

app.UseAuthentication();

        app.UseStaticFiles(new StaticFileOptions
        {
            OnPrepareResponse = ctx =>
            {
                if (ctx.Context.Request.Path.StartsWithSegments("/files/users"))
                {
                    ctx.Context.Response.Headers.Add("Cache-Control", "no-store");

                    if (!ctx.Context.User.Identity.IsAuthenticated)
                    {
                        // respond HTTP 401 Unauthorized with empty body.
                        ctx.Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        ctx.Context.Response.ContentLength = 0;
                        ctx.Context.Response.Body = Stream.Null;

                        // - or, redirect to another page. -
                        // ctx.Context.Response.Redirect("/");
                    }
                }
            }
    }
  • Related