How to protect user based folder and files in asp.net core 2.1 project

2.5k Views Asked by At

I have a folder named archive in my project and have a separate folder for each user. Sample folder structure;

Archive(Folder) => User1(Folder) => other folders => files
Archive(Folder) => User2(Folder) => other folders => files ...

I don't want a user to access other users' folders and files. I also want to prevent users who are not logged in to access the archive folder and its contents.

How can I do that?

2

There are 2 best solutions below

0
Edward On BEST ANSWER

For Static file authorization, you could refer Static file authorization.

For another option, you could write your own middleware to check the identity before app.UseStaticFiles();.

app.Map("/Archive", subApp => {
    subApp.Use(async (context, next) =>
    {
        if (!context.User.Identity.IsAuthenticated)
        {
            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
        }
        else if(context.Request.Path.StartsWithSegments("/Archive/User1") && context.User.Identity.Name != "User1")
        {
            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
        }
    });
});

app.UseStaticFiles();
0
Derviş Kayımbaşıoğlu On

creating permissions (file / folder level ownership) on operating system level can be cumbersome. If you decide to make this on OS level, you need your users to be domain authenticated / windows authentication (hence you need to use Windows or Active Directory Authentication)

Then you can easily give ownership to specificed files / folders and they cannot be reached by anyone else (other non-administrator users)


On the other hand, you may decide to create this mechanism on the application layer. In this case you only need to impersonate your application with an elevated user so that you can create files / folders. After that you need to create mechanism on the application level for identifying which users have access to where (folders). For this, I myself choose to use cached database table.