Haseeb Khan
Haseeb Khan

Reputation: 1040

Asp.net core Protect Folder out side wwwroot

I am creating an asp.net core app and using .Net5. I am uploading files outside www-root folder. Here is my configuration for the directory.

 app.UseFileServer(new FileServerOptions
            {
                FileProvider = new PhysicalFileProvider(@$"{Configuration["AppConfiguration:PhysicalDirectoryBasePath"]}"),
                RequestPath = new PathString("/app-data"),
                EnableDirectoryBrowsing = false
            });

I want to secure that folder so that no public user can access it. I want to check the header before accessing file like

header contains app-token then allow file to access otherwise not

I am unable to stop file accessing for public users. How to achieve this?

Upvotes: 0

Views: 1225

Answers (1)

Alexander
Alexander

Reputation: 9632

You can use middleware for this. Namely Map allows to execute required middleware for a path

app.Map("/app-data", appBuilder =>
{
    appBuilder.UseFilter();

    appBuilder.UseFileServer(new FileServerOptions
    {
        FileProvider = new PhysicalFileProvider($@"{Configuration["AppConfiguration:PhysicalDirectoryBasePath"]}"),
        RequestPath = new PathString(""), //empty, because root path is in Map now
        EnableDirectoryBrowsing = false
    });
}

Filter middleware

public class FilterMiddleware
{
    private readonly RequestDelegate _next;

    public FilterMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext httpContext)
    {
        if (httpContext.Request.Headers["API-KEY"] == "secret key")
        {
            //proceed serving files
            await _next(httpContext);
        }
        else
        {
            //return you custom response
            await httpContext.Response.WriteAsync("Forbidden");
        }
    }
}

Extension class allows to call UseFilter

public static class FilterMiddlewareExtensions
{
    public static IApplicationBuilder UseFilter(this IApplicationBuilder applicationBuilder)
    {
        return applicationBuilder.UseMiddleware<FilterMiddleware>();
    }
}

Upvotes: 0

Related Questions