views:

240

answers:

2

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

I used an alternative, set HttpContext.Session["CurrentUser"] = user. If I want to see if the session is authorized, I'd have to check that the HttpContext.User != null. But, I don't want to expose the authentication logic everywhere in the application. If I need to change that, it'd be messy.

Please help me solve this. One solution could be populating the HttpContext.User property of every request with the value of HttpContext.Session["CurrentUser"] at the beginning, but I don't know how to do it.

+1  A: 

The best way to do this is to write a custom authentication module and to hook it into your application. This module will execute before any request and will have a chance to set the HttpContext.User property as appropriate.

For example, consider the Forms Authentication module. Before your HTTP handler runs (be it an .aspx page, the MVC pipeline, etc.), it has a chance to intercept the request. It reads the value of a login cookie, decrypts and verifies the encrypted cookie value, and sets HttpContext.User if the checks pass. That way, when the handler runs and actually processes the request, the User property has already been set correctly.

In the end, what this will look like is that you don't need a custom authorization attribute on ASP.NET, as the [Authorize] attribute already provided in-box should work automatically with your custom authentication module. However, your AccountController.LogOn() method (or whatever you use in lieu of this) will need to communicate with the appropriate authentication provider that generates the token that will be validated by the authentication module. This should be the only place you'd need to write code different than what is provided in-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.

Levi
+3  A: 

Write the following method in the Global.asax's 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 that is inherited to your controllers (note: be sure to call FormsAuthentication.SetAuthCookie method when successfully validate your user login).

Alex LE