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

前端 未结 4 1015
情深已故
情深已故 2020-12-23 21:34

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

4条回答
  •  甜味超标
    2020-12-23 22:26

    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?

提交回复
热议问题