views:

42

answers:

1

Problem:

I have a webforms app where every page inherits from BasePage.cs I also have another class AuthenticatedBasePage.cs which inherits from BasePage.cs

BasePage.cs has some code which finds out if a Forms Authentication cookie is set, and if so, sets a IsAuthenticated boolean flag and a MyAppUser object (only has properties such as name, age, gendery) which means every page on the site can see if the user viewing the page is logged in or not, and if so, read the values of MyAppUser.

AuthenticatedBasePage has an additional feature where if anyone tries to browse to a page inheriting from this class are not authenticated, they are redirected to the login page with a 'returnurl' querystring variable set.

I would to have a similar setup in my MVC2 app. I've done a fair bit of reading that says I shouldn't reference HttpContext in my BaseController.cs (which all my controllers inherit from) as that means I can't unit test it. My first question is, how can I make the IsAuthenticated and MyAppUser objects available to every page? Secondly, how do I create pages which only authenticated users can access, and if they are not authenticated, they get redirected to the login page with the returnurl querystring variable set?

Many thanks, A.

P.S. I'm not using the MembershipSchema, I'm only using the FormsAuthentication.SetCookie method.

A: 

What you want is the Authorize attribute. This article has a great explanation of how to use it with forms authentication.

s1mm0t
Hi, I've already seen the Authorize attribute but it doesn't quite do what I want it to do. For example, if there is a User Profile page on my site, I want an 'edit' button to appear if the Currently logged in user is viewing their own user profile. In the View, I would like to access <%=CurrentUser.UserId%> or something to that effect. Using a webforms BasePage class made this easy, but I'm not quite sure how to replicate this behaviour in MVC2. My best effort involves creating a BaseViewModel with a CurrentUser property, which I manually set in the controller action.
Astrofaes
Have two actions, PublicProfile and Profile. If needs be, they can still use the same view.
s1mm0t