ebb
ebb

Reputation: 9377

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.

Upvotes: 6

Views: 2963

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038770

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.

Upvotes: 15

Russ Cam
Russ Cam

Reputation: 125488

Yes it is possible to hide images from unauthenticated users.

Depending on how your images are being displayed, you might hide them through

1.using the Authorize attribute on the controller action

2.wrapping the HTML in the view that will display the images in

if (User.Identity.IsAuthenticated) {
    // image HTML here   
}

You'll want to put the images somewhere where they cannot be viewed without being authenticated, such as in App_Data as Darin suggests.

Upvotes: 0

Related Questions