Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to store logged user information on ASP.NET MVC using Forms Authentication?

Tags:

I'm using ASP.NET MVC and Forms Authentication on my application. Basically I use FormsAuthentication.SetAuthCookie to login and FormsAuthentication.SignOut to logout.

In the HttpContext.Current.User.Identity I have stored the user name but I need more info about the logged user. I don't want to store my entire User obj in the Session because it might be big and with much more infomation than I need.

Do you think it's a good idea to create like a class called LoggedUserInfo with only the attributes I need and then add it to the Session variable? Is this a good approach?

Or do you have better ideas?

like image 727
Guillermo Guerini Avatar asked Nov 30 '09 18:11

Guillermo Guerini


People also ask

How can we implement keep me logged in ASP.NET MVC?

Put a checkbox to keep me logged in. Store id and password in cookies (key-value pair). When the user checked the checkbox of keep me logged in at the same time, store id and password in cookies. Later on when calling the Index action check if cookies of id and password is not null or blank then call the login method.

Why do we need forms authentication in MVC?

In application we have so many forms which we want to be accessed by only authentic user. In MVC as we know that we create action which calls view accordingly. So we have to authenticate the action that whether the authorize person is going to access the action or not.


1 Answers

I use this solution:

ASP.NET 2.0 Forms authentication - Keeping it customized yet simple

To summarize: I created my own IPrincipal implementation. It is stored in HttpContext.Current.Cache. If it is somehow lost, I have username from client side authorization cookie and can rebuild it. This solution doesn't rely on Session, which can be easily lost.

EDIT

If you want to use your principal in your controller and make it testable, you can do this:

    private MyPrincipal _myPrincipal;     MyPrincipal MyPrincipal     {         get         {             if (_myPrincipal == null)                 return (MyPrincipal)User;             return _myPrincipal;         }         set         {             _myPrincipal = value;         }     } 

In your test, you will set object prepared for testing. Otherwise it will be taken from HttpContext. And now I started thinking, why do I use Ninject to do it?

like image 52
LukLed Avatar answered Oct 20 '22 06:10

LukLed