0
votes

I have a set of files in the wwwroot folder. With webpack I generate js bundles with js.map files. I want to put security on the *.map files to only allow certain people to have access to it.

The documentation of ASP.NET core static files concludes that all files in wwwroot have no security. If security is needed advice is given to make an MVC controller and to put security on the action method.

I want to have the static files in wwwroot with one catch all *.js.map URLs which performs security and gives a notfound. How do I define this action method.

I don't want to put the map files in a different folder and to serve them differently.

1
If I apply following I'm already closer but I can not map files in sub folders: [Route("{url:regex((.*?).map.js)}")] - stephan.peters

1 Answers

0
votes

Define a route like this with a catchAll template and a constraint:

        app.UseMvc(routes =>
        {
            // https://haacked.com/archive/2008/07/14/make-routing-ignore-requests-for-a-file-extension.aspx/
            routes.MapRoute(
                name: "MapFiles", 
                template: "{*relativeFileUrl}", 
                defaults: new { controller = "FileSystem", action = "AccessDevFile" }, 
                constraints: new { relativeFileUrl = @".*\.js.map" }
            );
        });

The action method looks like this. If no access allowed we just return NotFound()

    public IActionResult AccessDevFile(string relativeFileUrl)
    {
        bool hasAccess = ... do your check ...
        if(hasAccess)
        {
            return base.PhysicalFile(_hostingEnvironment.WebRootPath + "\\" + relativeFileUrl.Replace("/", @"\"), "application/json");
        }

        return NotFound();
    }

Also make sure to have the UseMvc call before the UserStaticFiles call otherwise the action method can never be reached.