locked
Prevent direct access to files in a directory using asp.net core RRS feed

  • Question

  • User141727721 posted

    i have issue of direct access to files e.g when u click on the following link, it will access with out any restriction. i want to restrict from opening unless the user is login.

    if anyone helps me with that i will be very thank full.

    Tuesday, September 8, 2020 12:02 PM

All replies

  • User475983607 posted

    Noor Ahmad

    i have issue of direct access to files e.g when u click on the following link, it will access with out any restriction. i want to restrict from opening unless the user is login.
    https://students.aiu.edu/submissions/profiles/UB66961BBU76023/Docs/201361475352_9272007-163410-5-Important20Supporting20Documents20for20a20Bachelors20Program.pdf

    if anyone helps me with that i will be very thank full.

    Place the files outside the wwwroot folder.   Either write an action that returns the files or craft a custom middleware.  

    https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.fileresult?view=aspnetcore-3.1

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1#security-considerations-for-static-files

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.1

    Tuesday, September 8, 2020 1:39 PM
  • User141727721 posted

    i tried all this, not help full.

    Tuesday, September 8, 2020 2:46 PM
  • User475983607 posted

    Noor Ahmad

    i tried all this, not help full.

    What's "not helpful"?  Please share the code you tried.   

    Below is an example of using an action to return a file.

        public class FileController : Controller
        {
            [Authorize]
            public async Task<IActionResult> Index(string filename)
            {
                string filePath = $@"c:\some\folder\{filename}";
                string content = await System.IO.File.ReadAllTextAsync(filePath);
                return File(content, "application/octet-stream");
            }
        }

    You might also use an Id which is good if you store the file path in a table which relates to the user that can access the file.

           [Authorize]
            public async Task<IActionResult> Index(int id)
            {
                string filePath = GetFileById(id, User.Identity.Name);
                string content = await System.IO.File.ReadAllTextAsync(filePath);
                return File(content, "application/octet-stream");
            }

    The [Authorize] attribute restricts access to only authenticated users.  You can also restrict access to roles and claims using standard ASP.NET security policies.

    https://docs.microsoft.com/en-us/aspnet/core/security/authorization/claims?view=aspnetcore-3.1

    Lastly, you can write middleware if you need custom logic within the HTTP pipeline as clearly and openly explained in the links above.

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1#static-file-authorization

    Tuesday, September 8, 2020 3:46 PM
  • User141727721 posted

    its look helpfull, but i am using asp.net core 2.2, the fallbackpolicy is available for cor 3.1 and above. 

    Wednesday, September 9, 2020 6:02 AM
  • User141727721 posted

    i have tried the following code.it redirects me to login page, while the user is logged in already. my identity is claim based, how to integrate the custom policy with current user logged in.

    //configure services

    public void ConfigureServices(IServiceCollection services)
     {
      services.AddAuthorization(options =>
                {
                    options.AddPolicy("Authenticated", policy => policy.RequireAuthenticatedUser());
                });
    }
    

    //configure method

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
       {
                app.UseProtectFolder(new ProtectFolderOptions
                {
                    Path = "/MyStaticFiles",
                    PolicyName = "Authenticated"
                });
                app.UseStaticFiles();
               
       }

    //my protectFolder Class

    public class ProtectFolderOptions
        {
            public PathString Path { get; set; }
            public string PolicyName { get; set; }
        }
        public static class ProtectFolderExtensions
        {
            public static IApplicationBuilder UseProtectFolder(
                this IApplicationBuilder builder,
                ProtectFolderOptions options)
            {
                return builder.UseMiddleware<ProtectFolder>(options);
            }
        }
        public class ProtectFolder
        {
            private readonly RequestDelegate _next;
            private readonly PathString _path;
            private readonly string _policyName;
    
            public ProtectFolder(RequestDelegate next, ProtectFolderOptions options)
            {
                _next = next;
                _path = options.Path;
                _policyName = options.PolicyName;
            }
    
            public async Task Invoke(HttpContext httpContext,
                                     IAuthorizationService authorizationService)
            {
                if (httpContext.Request.Path.StartsWithSegments(_path))
                {
                    var authorized = await authorizationService.AuthorizeAsync(
                                        httpContext.User, null, _policyName);
                    if (!authorized.Succeeded)
                    {
                        await AuthenticationHttpContextExtensions.ChallengeAsync(httpContext);
                        return;
                    }
                }
    
                await _next(httpContext);
            }
        }

    Wednesday, September 9, 2020 9:11 AM