Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to maintain a user id (MVC)

I use FormsAuthentication, but I've added a custom MemberShipProvider to validate against a custom User Table.

All tables containing "user data" have a idUser column, so I need to maintain the user id in order to present the user with his data.

Previously I've used a session variable (ASP.NET Webform), but as I am rewriting the webapplication to MVC, I'd like to ask what is generally considered as the best approach for this.

Is session variable still the best place to hold the idUser, or should I add a custom "Current.User.Identity" which in addition to username also holds a public userId ??

Or should I choose a completly different approach?

like image 573
Kman Avatar asked Mar 12 '12 22:03

Kman


People also ask

What is identity authentication in MVC?

Identity in MVC 5 Identity is a secured way of authentication methods in web applications. It is used for identifying the authorized user. Background. There are different ways of creating an Identity in applications, but this article explains how to create it using OWIN in ASP.NET MVC.


1 Answers

I had the same question when I implemented a custom membership provider for MVC. I ended up doing two things. I store the user's Id in the ProviderUserKey field of the MembershipUser object. See provideruserkey. Then to answer your question, yes I created a custom principal from System.Web.Security.IPrincipal, though I later inherited from System.Web.Security.RolePrincipal instead since I wanted support for Roles.

public class MyPrincipal : RolePrincipal
{
    public Guid Id { get; set; }

    public MyPrincipal(string providerName, IIdentity identity, Guid id) : base(identity)
    {
        Id = id;
    }
}

Update: The reason I didn't want to use session in my case is because I've disabled it for the app. I've read that the core concept behind MVC is that separation of concerns, and that is closely models the way the web works, which is stateless. Though I can't remember where I read that now that I try to remember. However I do remember also reading that if you can eliminate the session you should do so. It will allow IIS to serve up simultaneous requests from your app rather than having to wait for one request to finish (and release the user's session) before the next request can use the session and send it's response. The biggest impact of which is loading page content using Ajax.

like image 168
Nick Albrecht Avatar answered Dec 02 '22 03:12

Nick Albrecht