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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With