0

I am experimenting with different ways to secure an Angular CLI app with .NET Core Authorization.

To make it as secure as possible, I would like to keep all of the Angular CLI output files from being publicly available and keep them in the default "dist" folder preconfigured by the CLI.

I can load the index.html from an authorized controller by returning a PhysicalFileResult...

public IActionResult Index()
{
    return PhysicalFile(Path.Combine(Directory.GetCurrentDirectory(), "dist", "index.html"),"text/HTML");
}

But I get 404s on all of the bundle.js files when the page loads.

Is it possible to serve the app this way without involving the static file middleware or making the files publicly available (preferably without having to manually change the src for each bundled js file in index.html)?

David
  • 797
  • 2
  • 8
  • 23

2 Answers2

0

Take a look at this article from the asp.net core docs (excerpt included below): https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files#static-file-authorization


enter image description here

univ
  • 717
  • 4
  • 12
  • I read that, which prompted me to learn to use PhysicalFile(), which returns a PhysicalFileResult. https://medium.com/@tanaka_733/static-file-authorization-in-asp-net-core-mvc-26c1069073c1 It works, and I can serve the index.html file from anywhere on the file system but the html file can't load the javascript files that are in the same directory. I feel like there should be a way to serve an entire directory from the controller action. – David Jul 07 '17 at 21:01
0

Just place your authorization middleware before the static one.

// has to be first so user gets authenticated before the static middleware is called
app.UseIdentity();

app.Use(async (context, next) => 
{
    // for pathes which begin with "app" check if user is logged in
    if(context.Request.Path.StartsWith("app") && httpContext.User==null)
    {
        // return "Unauthorized"
        context.Response.StatusCode = 401;
        return;
    }

    // If user is logged in, call next middleware
    await next.Invoke();
});

app.UseStaticFiles();
Tseng
  • 61,549
  • 15
  • 193
  • 205