h bob
h bob

Reputation: 3780

Serving "private" images via a secured ChildAction

Some of our site's images are "private" and should only be served to authenticated and authorized users.

So they are located in /App_Data, and are rendered via this secured action:

//[ChildActionOnly]
[Authorize]
[HttpGet]
[Route("Image")]
public virtual FileResult Image(string path) {
  return base.File(Server.MapPath(path), "image/jpg");
}

In a view, I have <img src="@Url.Action(Image(...))"> which correctly serves that "private" image. No public user can see it.

Problem is I don't want my authenticated users to be able to navigate to it directly, so I added the [ChildActionOnly] attribute. But when I do that, it fails to load.

How can I serve these images to private users, but make it inaccessible from a request?

Upvotes: 0

Views: 44

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239270

ChildActionOnly means that the action can only be called via Html.Action. Since you can't load an image that way, it will never work. If you want the action protected, then all you need is the Authorize attribute:

[Authorize]
[HttpGet]
[Route("Image")]
public virtual FileResult Image(string path) {
    return base.File(Server.MapPath(path), "image/jpg");
}

UPDATE

I think I understand what you mean now. You're saying you only want to be able load it on the page, but you don't want some one to be able to copy the href and load it in a separate window or tab? Is that correct? If so, then unfortunately, that's simply not possible. A request is a request, whether it's done via HTML on your page or manually via a user, there's no difference.

Upvotes: 1

Related Questions