Base solution for your next web application
Open Closed

Static File Authentication #10861


0
KPCS created

Hi Team,

There is direct URL access issue in asp.net zero project, where user can access static files without authentication.

For example any one can access this URL: d6be4d82.demo.aspnetzero.com/assets/sampleFiles/ImportUsersSampleFile.xlsx

We want to authentication checks for this URL, guide us how we can achieve this.

Thanks,

Kind Regards, Kumar Prashant


1 Answer(s)
  • 0
    ismcagdas created
    Support Team

    Hi,

    You can modify the StaticFile middleware as shown below;

    app.UseStaticFiles(new StaticFileOptions()
            {
                OnPrepareResponse = (context) =>
                {
                    if (!context.Context.User.Identity.IsAuthenticated && context.Context.Request.Path.StartsWithSegments("/assets"))
                    {
                        throw new Exception("Not authenticated");
                    }
                }
            });
    

    Or you can even write a custom middle ware which must be placed before staticFiles middleware;

    app.Use(async (context, next) =>
                   {
                       if (!context.User.Identity.IsAuthenticated
                           && context.Request.Path.StartsWithSegments("/assets"))
                       {
                           throw new Exception("Not authenticated");
                       }
                       await next.Invoke();
                   });