I have a very simple asp.net core 2.0 application and what it looks like a very simple problem, but I can't find the solution.
My application store diferent private images for users like photo, copy of their id...those images of course have to be private and only the web application can show them in certain pages. For example the administrator can see them when browsing the users in the admin panel, or a user can see his images...
The files are in a folder "users/1/photo.jpg" or "users/243/id.jpg". Of course those folders have to be private and you can't browse them.
How can I do so when I use a image tag I can see the image:
<img src="???">
Without showing the real path and also preventing anyone to access that file but the pages I want.
Thanks.
UPDATE
First of all, thanks to Mark Redman and T.S., you helped a lot.
Finally what I'm doing is to have the sensible images outside the StaticFiles public folder and the non-sensible ones in the wwwroot folder.
PART 1. SENSIBLE IMAGES
For the sensible images I'm using a IActionResult to return the file, but after I encrypt the file name. This is just an example...
public IActionResult ViewUser(int id)
{
var model = new Model();
....
model.EncryptedId = _protector.Protect(id.ToString("D6"));
return View(model);
}
This way I can return the encrypted id to retrieve the image I want without publishing the real id.
In my View:
<img src="/home/GetImage?id=@Model.EncryptedId" />
And the GetImage would look like this:
public IActionResult GetImage(string encryptedId)
{
var decryptedId = _protector.Unprotect(encryptedId);
var file = Path.Combine(_hostingEnvironment.ContentRootPath, "MyPrivateFiles", decryptedId + ".jpg");
return PhysicalFile(file, "image/jpeg");
}
This way, as far as I understand:
- I'm protecting my private files by not storing in a public folder such as wwwroot, so no one can download them directly.
- Also no one can get the id of an existing user and try to call my Action GetImage?id=232 because I have encrypted that id.
Other protection level I can have is only authorize certain users to access the GetImage Action, for example allowing users only to get their images or allowing administrators to download any.
PART 2. NON SENSIBLE IMAGES
For the non sensible images (such as user public photos) I'm storing them in the wwwroot because I need them to be public.
Using the asp-append-version="true" I can cache images, which is a very good improvement of this Asp.Net Core.
The only thing left for me would be to obfuscate those image names so I'm not showing "domain.com/users/1234.jpg" and show, for example, "domain.com/users/sdfjknkjSD2.jpg".
I don't know how to do this WITHOUT LOSING the advantage of the caching. Is there a way to do this?
Thanks in advance.