Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ASP.NET MVC OutputCache while varying View content based on whether user is authenticated

I'm building an ASP.NET MVC 2 site where I'm using the OutputCache parameter heavily. However, I have a concern: using such caching may interfere with authentication.

On all of my pages, I display whether the user is logged in or not. Furthermore, in some of my Views, I do filtering based on user role to determine whether or not to display some page content (for example, the Edit link on one of my pages is only shown to users in the roles of Moderator or Administrator).

Will using OutputCache interfere with this dynamic changing of my Views? If so, how can I resolve this problem without eliminating caching?

like image 630
Maxim Zaslavsky Avatar asked Aug 09 '10 21:08

Maxim Zaslavsky


2 Answers

The [OutputCache] and [Authorize] attributes play well with one another. The AuthorizeAttribute.OnAuthorization() method sets a hook into the output caching system that forces the authorization filter to re-run before the page is served from the cache. If the authorization filter logic fails, it will be treated as a cache miss. If the authorization logic succeeds, the page will be served from the cache. So if you have [Authorize(Roles = "Moderator, Administrator")] and [OutputCache] on an action, the page will not be served from the cache unless the current user is in the Moderator or Administrator roles.

Note that this does not vary by user or role; it's literally re-running the original check. Imagine that User A (who is a Moderator) comes in and causes the page to be cached. Now User B (who is an Administrator) comes in and hits the cached page. The [Authorize] check will succeed since both Administrator and Moderator are allowed, and the response served to User B will contain the exact same contents as the response that was served to User A.

Note that response substitution does not work in MVC 2. If you're serving potentially sensitive data, the best bet here is not to cache it. If you absolutely need to cache, you can mimic something similar to response substitution by using an AJAX callback to dynamically fill in the missing data.

like image 121
Levi Avatar answered Nov 15 '22 04:11

Levi


I believe what you need is ASP.NET donunt caching. See here for a good explaination. I wouldn't be suprised if SO uses something like this for the top bar area.

like image 21
madcapnmckay Avatar answered Nov 15 '22 04:11

madcapnmckay