Mike Stephenson
Mike Stephenson

Reputation: 679

How to protect static pages from being served to unauthenticated users in ASP.NET Core 3.x?

I have an ASP.NET 3.1 web app. I also have a web help documentation system created from the Help & Manual documentation system. These help files include html, JavaScript, image files and possible some videos and PDF files. The web help system is a project created outside of Visual Studio. Normally, I'd use a subdomain but I figure I can deploy it to a folder within the main web app for the purposes of taking advantage of ASP.NET Identity which I'm using for authentication and authorization.

I need to protect all of these assets from unauthenticated users as there is proprietary data but I'm unsure how this can be done. Hoping for a simple and elegant solution.

Upvotes: 0

Views: 280

Answers (1)

Yinqiu
Yinqiu

Reputation: 7190

I think you can get these files by writing an Action, and then adding Attribute to the Action. Here is an example of mine. I have a json file under wwwroot, and I want to have users with the role of "Admin" To access it.Here is my action

    [Authorize(Roles = "Admin")]
    public IActionResult GetFiles()
    {
        var file = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "json.json");
        return PhysicalFile(file, "application/octet-stream");
    }

About PhysicalFile method, you can check this link https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.controllerbase.physicalfile?view=aspnetcore-3.1

Upvotes: 1

Related Questions