HttpContext.Current.User != HttpContext.User?

前端 未结 1 1300
挽巷
挽巷 2020-12-31 17:24

Is HttpContext.Current.User in global asax not the same as HttpContext.User in an action method? I assigned the user some roles, but they

相关标签:
1条回答
  • 2020-12-31 17:43

    Your question tags say "aspnet-mvc (3 and 4)", so do you have the option of using the following to make your life easier? If you are using Simple Membership from the MVC 4 Internet Application template in VS2012 this will just work out of the box for you):

    • WebSecurity.CreateUserAndAccount(name, password) - to create a user
    • Roles.AddUserToRole (and AddUserToRoles) - add a user to a role
    • Roles.IsUserInRole - tests if a user is in a role
    • [Authorize(Roles = "admin")] - [Authorize] can enforce roles on an entire controller, or on an action

    CreateUserAndAccount has the advantage that it's easy to set properties for the UserProfile as well, for example:

    WebSecurity.CreateUserAndAccount(newUser.UserName, newUser.Password,
        new { FullName = newUser.FullName, Email = newUser.Email, Timezone = newUser.TZ });
    Roles.AddUserToRoles(newUser.UserName, new[] {"admin", "user"});
    

    Edit, I realise the above doesn't answer your original question about .User property equivalence.

    HttpContext in a Controller is a property: Controller.HttpContext. HttpContext in global.asax.cs is the static class, so that's why you use HttpContext.Current. They refer to the same thing.

    If you run the following code, you can see they are apparently the "same principal". So the question is what happened to the roles you assigned?

    protected void Application_AuthenticateRequest(object sender, EventArgs e) {
        ...
        FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;
        string[] roles = new string[] { "admin", "user" };
        identity.Label = "test label";
        System.Security.Principal.GenericPrincipal ppl = new System.Security.Principal.GenericPrincipal(identity, roles);            
        HttpContext.Current.User = ppl;
    ... }
    
    public ActionResult Index() {
        bool isAdmin = HttpContext.User.IsInRole("admin");
        bool isAdmin2 = System.Web.HttpContext.Current.User.IsInRole("admin");
        System.Web.Security.FormsIdentity identity = (System.Web.Security.FormsIdentity)HttpContext.User.Identity;
    
        // The label is carried through from Application_AuthenticateRequest to Index.
        string label = identity.Label;
    }
    

    The problem is, you assigned a GenericPrincipal to .User. Depending on the RoleProvider, this can be overwritten (e.g. by the RoleManagerModule) during PostAuthenticateRequest and (for example) turned into a RolePrincipal. This can then defer back to the database (again depending on provider) to get the roles, so over-writing your roles. If you do the work in Application_OnPostAuthenticateRequest you might be ok.

    0 讨论(0)
提交回复
热议问题