There is no way to protect static files on ASP.NET Core. It goes without saying, however, that that doesn't mean you can't do it. Essentially, you have the following two options:
- Keeping the files that you want to serve outside the wwwroot folder and using a controller action to retrieve them; this action should enforce any security mechanism you want
- Using a middleware component to check access to your files and optionally restrict access to them
We will see each process in the next sections.
Using an action to retrieve files
So, you want to use an action method to retrieve a file. Either decorate this action method with an [Authorize] attribute or check for fine-grained access inside it (IAuthorizationService.AuthorizeAsync). Have a look at the following code:
private static readonly IContentTypeProvider _contentTypeProvider =
new FileExtensionContentTypeProvider();
[Authorize...