I prefer option number 2 (use Thread.CurrentPrincipal outside of the web tier). as this will not get your service level and data level methods. with bonuses: you can save your roles + additional information in the user principle;
To ensure that Thread.CurrentPrincipal in your service and data layer matches your web layer; you can set your HttpContext.Current.User (Context.User) to Global.asax (Application_AuthenticateRequest). Another alternative place where you can install this is added at the bottom.
code example:
//sample synchronizing HttpContext.Current.User with Thread.CurrentPrincipal protected void Application_AuthenticateRequest(Object sender, EventArgs e) { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; //make sure principal is not set for anonymous user/unauthenticated request if (authCookie != null && Request.IsAuthenticated) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); //your additional info stored in cookies: multiple roles, privileges, etc string userData = authTicket.UserData; CustomPrincipal userPrincipal = PrincipalHelper.CreatePrincipal(authTicket.Name, authTicket.UserData, Request.IsAuthenticated); Context.User = userPrincipal; } }
Of course, you must first implement your registration form in order to create authorization cookies containing your user principle.
Application_AuthenticateRequest will be executed for any request to the server (css files, javascript files, image files, etc.). To limit this functionality only to the action of the controller, you can try to set the user principle in ActionFilter (I have not tried this). What I tried installs this functionality inside Interceptor for Controllers (I use Castle Windsor for my dependency injection and aspect-oriented programming).
kite
source share