2

At what point should I be checking for my cookie in my mvc app? Basically what I wish to do for each request is check to see if there is a cookie and if so show their name on the screen somewhere if not and the page requires the user to be logged in redirect them to a login page.

I DON'T want to use FormsAuthentication as I wish to create and use my own IPrinciple object I 'm just not sure whether I should be setting these in a base controller class or creating my own Authorize attribute and doing the checks in there.

My initial thoughts are that I should be doing this in the base controller class as this is similar to the base page in webforms where I override oninit.

1

1 Answer 1

3

Do not attempt to do authentication in a base controller class. In a situation where an action result is cached, your action will not run at all, and no controller will ever be instantiated. Therefore, authentication done inside the controller is broken by design.

The correct way to customize authentication, for many reasons, is to create a custom authentication provider. I've explained the reasons why and given links to simple examples of how to do this in the post linked above.

In short, using this method:

  • Has the right level of modularity
  • Works with caching
  • Works with regular ASP.NET, as well as with MVC
Sign up to request clarification or add additional context in comments.

7 Comments

Does creating my own provider handle creating the correct IPrincipal objects that are accessible via Context.User? Also what about creating my own cookies and linking them in with this new provider?
You can do all of this in a custom provider, yes.
Whereabouts do I take care of all this, I have found examples of subclassing the membership provider but don't see any examples of where I would set up my cookies and create my own iprincpal objects, do you know of any examples of this.
You should not create cookies (you can, but you shouldn't). Cookies are encrypted. Most people (even experts) implement encryption incorrectly, so you should let the Membership system do this for you. You should, though, add the info you need in your cookies, either in Membership (if directly authentication related) or in Profiles (if not authentication related). There's a custom principal implementation here: msdn.microsoft.com/en-us/magazine/cc163807.aspx
"Cookies are encrypted" should probably read "the cookies created by Membership containing authentication tokens are encrypted," for clarity.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.