How do you enable unit test web page authorization using ASP.NET MVC?

Say you have a profile page that only the owner of this profile can access. This profile page is located at:

User / Profile / {} user ID

Now, I suppose, to prevent other users from accessing this page, you can structure your UserController profile profile function to check the current session ID:

HttpContext.Current.User.Identity.Name

If the identifier matches the identifier in the URL, you continue. Otherwise, you are redirected to some kind of error page.

My question is: how do you unit test something like this? I assume that you need to use some kind of dependency injection instead of the HttpContext in the controller to check, but I do not quite understand what the best way to do this. Any advice would be helpful.

+6
tdd asp.net-mvc
source share
4 answers

I ended up moving to "UserNameFilter" as shown in the Kazi Manzur blog post . Works like a charm and is easy to unit test.

+1
source share

Perhaps you can do this using fake for the controller context. Check out this article: http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx

+1
source share

The link above is good. I would also add that instead of programmatically checking the value of User.Identity.Name, you should use the Authorize attributes, as indicated in the article:

http://weblogs.asp.net/scottgu/archive/2008/07/14/asp-net-mvc-preview-4-release-part-1.aspx

+1
source share

This is where it is mocked, with a fake HttpContext.

0
source share

All Articles