views:

49

answers:

2

I am working on an ASP.NET MVC application. I have implemented custom membership provider, principal and identity. In the custom provider I replace the HttpContext.Current.User in the ValidateUser() method as follows:

public sealed class CustomMembershipProvider : MembershipProvider {  
    ...  
    public override bool ValidateUser(string username, string password) {  
      ...  
      CustomIdentity identity = new CustomIdentity(...);  
      CustomPrincipal cu = new CustomPrincipal(identity);  
      HttpContext.Current.User = cu;  
      ...  
    }  
    ...  
}

In the AccountController (calls the custom membership provider) I am able to access the custom identity as follows:

public class AccountController : BaseController {  
  ...  
  public ActionResult LogOn(string userName,   
                            string password,   
                            bool rememberMe,   
                            string returnUrl) {  
    ...  
    CustomIdentity ci = (CustomIdentity)HttpContext.User.Identity;  
    ...  
  }  
  ...  
}

All my controllers inherit the BaseController which calls a custom attribute as follows:

[CustomAttribute]  
public abstract class BaseController : Controller {  
  ...  
}  

I want my other controllers to access the custom identity within the custom attribute after it has been set by the AccountController as follows:

public class CustomAttribute : ActionFilterAttribute {  
  public override void OnActionExecuting(ActionExecutingContext filterContext) {  
    base.OnActionExecuting(filterContext);  
    CustomIdentity ci = filterContext.HttpContext.User.Identity as CustomIdentity;  
    ...  
    }  
  }  
}  

What I have found is that filterContext.HttpContext.User is still set to GenericPrincipal and not my CustomPrincipal. So my custom identity is not accessible within my attribute filter. What do I have to do so that my CustomPrincipal is accessible within my attribute filter?

Thanks in advance.

+1  A: 
I'm looking for something very similar, a custom principal. From all of my searching, both within StackOverflow and on the web, this is the recommended way to handle a custom principal.
Jim Gilmartin
A: 

I don't know if this is "better" way, but it worked for me so far. I create a static UserContext class that has CurrentUser property. There I store the user entity I get from database and use it for user info data and authorization. I only use the HttpContext.Current.User to check authentication.

Now the CurrentUser property stores my user object in HttpContext's Items colletion (I have a wrapper around that so I can make it unit testable).

Necros