Set HttpContext.User for the session

I implemented user authentication in ASP.NET MVC. If a valid user tries to log in, I set HttpContext.User = user in the login method of AccountController. But he remains there only for this request. How can I set it for a session?

I used an alternative, set HttpContext.Session["CurrentUser"] = user . If I want to know if a session is allowed, I need to check that HttpContext.User != null . But I do not want to reveal the authentication logic everywhere in the application. If I need to change this, it will be dirty.

Please help me solve this problem. One solution might be to populate the HttpContext.User property for each request with the HttpContext.Session["CurrentUser"] value at the beginning, but I don't know how to do it.

+7
asp.net-mvc
source share
2 answers

Write the following method in the Global.asax application class

 protected void Application_BeginRequest(Object sender, EventArgs e) { HttpContext.Current.User = HttpContext.Session["CurrentUser"]; } 

or you can use the User property of System.Web.Mvc.Controller, which is inherited from your controllers (note: do not forget to call the FormsAuthentication.SetAuthCookie method when you successfully confirm your user name).

+11
source

The best way to do this is to write your own authentication module and connect it to your application. This module will be executed before any request and will be able to set the corresponding HttpContext.User property.

For example, consider the forms authentication module. Before starting your HTTP handler (whether it is an .aspx page, an MVC pipeline, etc.), it has a chance to intercept the request. It reads the cookie value for logging in, decrypts and checks the value of the encrypted cookie, and sets HttpContext.User if the checks pass. Thus, when the handler starts and actually processes the request, the User property is already set correctly.

In the end, it will look like this: you do not need a special authorization attribute on ASP.NET, since the [Authorize] attribute already provided in the box should automatically work with your custom authentication module. However, your AccountController.LogOn () method (or what you use instead) will need to contact the appropriate authentication provider, which generates a token that will be verified by the authentication module. This should be the only place you need to write code other than what is provided in the box.

See http://social.msdn.microsoft.com/Search/en-US?query=http%20modules and http://social.msdn.microsoft.com/Search/en-US?query=custom%20authentication%20asp .net for more information.

+6
source

All Articles