I have placed few folders having static content in wwwroot. For some folders i need that user is authenticated to view those.
For this i have added code in Startup like below.
app.UseStaticFiles(new StaticFileOptions()
{
OnPrepareResponse = ctx=>
{
if(!ctx.Context.User.Identity.IsAuthenticated && ctx.Context.Request.Path.Value("admin/manuals"))
{
ctx.Context.Response.Redirect("/");
}
}
}
Although i am authenticated but i am always getting the isAuthenticated false. Why i am getting this also..
Also what can be the better way to handle such scenario.
Here are two ways to serve files based on authorization:
The fist way like what you did to configre the static files middleware.
Be sure call
UseStaticFiles
afterUseAuthorization
:The second way is to serve them via an action method to which authorization is applied and return a FileResult object:
Reference:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1#static-file-authorization