SGhimire
SGhimire

Reputation: 1

Role based Access to Static Content in ASP.NET CORE

Is there any way I can give access to static content based on their role. In my application, the authentication is done through Azure Active AD and the contents should be accessed based on their role e.g. employee should access all employee pages and students should access student pages. This is how my solution explorer looks like. Solution Explorer

I know this is duplicate of Secure requests to .html files in ASP.NET Core but I couldn't find any approach to implement the solution. I have made new folder intranet outside the wwwRoot to serve my static content but still need to know how can I authorize the user and and serve role based static files.

Upvotes: 0

Views: 428

Answers (1)

Zhi Lv
Zhi Lv

Reputation: 21636

As the document said, you could store the static files outside of wwwroot and any directory accessible to the Static File Middleware (for example: MyStaticFiles folder, like this), then, you could serve them via an action method to which authorization is applied and return a FileResult object:

    [Authorize(Roles = "User")]
    public IActionResult BannerImage()
    {
        var filePath = Path.Combine(
            _env.ContentRootPath, "MyStaticFiles", "images", "Image1.jpg");

        return PhysicalFile(filePath, "image/jpeg");
    }

Then, you could view image by click the following link:

   <a asp-action="BannerImage" asp-controller="Home">View Image</a>

[Note] After using the above method, if the authorize not working, try to clear the cache, perhaps the issue is related to the browser cache. Besides, if you meet the "HTTP Error 404.15 - Not Found" error, try to add [AllowAnonymous] attribute for other controller action method.

Upvotes: 0

Related Questions