Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Image + Authenticated Users Only

is it possible to somehow only allow authenticated users to view certain images? I'm building a web gallery at the moment, and I dont want non-authenticated users to be able to see the images.

like image 365
ebb Avatar asked Apr 09 '11 17:04

ebb


1 Answers

You could put those images somewhere on the server where users don't have access (like for example the ~/App_Data folder) in order to prevent direct access to them and then use a controller action to serve them. This action will be decorated with an Authorize attribute to allow only authenticated users to call it:

[Authorize]
public ActionResult Image(string name)
{
    var appData = Server.MapPath("~/App_Data");
    var image = Path.Combine(appData, name + ".png");
    return File(image, "image/png");
}

and then:

<img src="@Url.Action("Image", "SomeController", new { name = "foo" })" alt="" />

Inside the view you could also test whether the user is authenticated before displaying the image.

like image 78
Darin Dimitrov Avatar answered Sep 17 '22 12:09

Darin Dimitrov