David
David

Reputation: 817

.NET Core serving HTML file outside wwwroot can't load JS files

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)?

Upvotes: 0

Views: 2024

Answers (2)

Tseng
Tseng

Reputation: 64121

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

Upvotes: 0

univ
univ

Reputation: 737

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

Upvotes: 0

Related Questions