User.IsInRole()不工作角色分配后的权利,但重新登录后不 [英] User.IsInRole() does not work right after role assignment, but does after re-login

查看:171
本文介绍了User.IsInRole()不工作角色分配后的权利,但重新登录后不的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我使用Unity容器创建OWIN /标识对象和解决所有依赖ASP.NET MVC 5应用程序。

问题是,当我注册成为新用户并分配给他这样的角色

  userManager.AddToRole(user.IdNEWUSER);
...
等待userManager.UpdateAsync(用户);

它实际上创建了AspNetUserRoles表中的记录,但之后,如果我检查他的角色User.IsInRole(NEWUSER)我得到假的,除非我登录出来,然后再次登录,那么它是正确的。

我想这个问题可能是与身份对象(的UserManager,RoleManager等)​​,生命周期管理的统一环境。

UnityConfig.cs

 公共静态无效RegisterTypes(IUnityContainer容器)
{
    //的DbContext
    container.RegisterType<的DbContext,AppEntitiesDbContext>();
    container.RegisterType< AppIdentityDbContext>();    //身份
    container.RegisterType&所述; IUserStore&下; ApplicationUser>中UserStore&所述; ApplicationUser>>(
                新InjectionConstructor(typeof运算(AppIdentityDbContext)));    container.RegisterType< IAuthenticationManager>(
                新InjectionFactory(C =方式> HttpContext.Current.GetOwinContext()认证));    container.RegisterType< IRoleStore< IdentityRole,串>中Rolestore的< IdentityRole>>(
                新InjectionConstructor(typeof运算(AppIdentityDbContext)));     container.RegisterType< ApplicationUserManager>();
     container.RegisterType< ApplicationSignInManager>();
     container.RegisterType< ApplicationRoleManager>();
}

IdentityConfig.cs
(我用<添加键=owin:AppStartupVALUE =MyApp.IdentityConfig/> 在Web.config中)

 公共类IdentityConfig
{
    公共无效配置(IAppBuilder应用程序)
    {
        变种容器= UnityConfig.GetConfiguredContainer();        app.CreatePerOwinContext(()=> container.Resolve&下; AppIdentityDbContext>());
        app.CreatePerOwinContext(()=> container.Resolve&下; ApplicationUserManager>());
        app.CreatePerOwinContext(()=> container.Resolve&下; ApplicationSignInManager>());
        app.CreatePerOwinContext(()=> container.Resolve&下; ApplicationRoleManager>());        app.UseCookieAuthentication(新CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LOGINPATH =新PathString(/帐号/登录)
        });
    }
}


解决方案

这是因为使用从用户对象(的IPrincipal)什么是看用户的身份象征对于当前的HTTP请求,而不是用户的持续值

当您登录该令牌会从角色和其他权利要求所造成。如果改变在数据库中的用户的角色令牌需要被重新创建并设置为在用户的新的标识。

当您更改用户身份的一部分。刚刚签署出来/回废止旧令牌,并重新发出一个新的。

 专用异步任务SignInAsync(用户用户,布尔isPersistent)
    {
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        VAR身份=等待UserManager.CreateIdentityAsync(用户,DefaultAuthenticationTypes.ApplicationCookie);
        AuthenticationManager.SignIn(新AuthenticationProperties(){IsPersistent = isPersistent},身份);
    }

In a ASP.NET MVC 5 application I'm using Unity container to create OWIN/Identity objects and resolve all the dependencies.

The problem is when I register as a new user and assign him a role like this

userManager.AddToRole(user.Id, "NewUser");
...
await userManager.UpdateAsync(user);

it actually creates a record in AspNetUserRoles table, but right after that if I check his role with User.IsInRole("NewUser") I get false, unless I log out and then log in again, then it is true.

I guess the problem could be with Identity objects (UserManager, RoleManager, etc.) lifetime management in Unity context.

UnityConfig.cs

public static void RegisterTypes(IUnityContainer container)
{
    // DbContext
    container.RegisterType<DbContext, AppEntitiesDbContext>();
    container.RegisterType<AppIdentityDbContext>();

    // Identity
    container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(
                new InjectionConstructor(typeof(AppIdentityDbContext)));

    container.RegisterType<IAuthenticationManager>(
                new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));

    container.RegisterType<IRoleStore<IdentityRole, string>, RoleStore<IdentityRole>>(
                new InjectionConstructor(typeof(AppIdentityDbContext)));

     container.RegisterType<ApplicationUserManager>();
     container.RegisterType<ApplicationSignInManager>();
     container.RegisterType<ApplicationRoleManager>();
}

IdentityConfig.cs (I use <add key="owin:AppStartup" value="MyApp.IdentityConfig" /> in Web.config)

public class IdentityConfig
{
    public void Configuration(IAppBuilder app)
    {
        var container = UnityConfig.GetConfiguredContainer();

        app.CreatePerOwinContext(() => container.Resolve<AppIdentityDbContext>());
        app.CreatePerOwinContext(() => container.Resolve<ApplicationUserManager>());
        app.CreatePerOwinContext(() => container.Resolve<ApplicationSignInManager>());
        app.CreatePerOwinContext(() => container.Resolve<ApplicationRoleManager>());

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login")
        });
    }
}

解决方案

That's because using anything from the User object (IPrincipal) is looking at the identity token of the user for the current HTTP request, not the persisted values of the user.

When you log in that token gets created from the roles and other claims. If you change the user's roles in the database the token needs to be recreated and set as the user's new identity.

When you change a part of the user's identity. Just invalidate the old token and re-issue an new one by signing them out/back in.

private async Task SignInAsync(User user, bool isPersistent)
    {
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
        AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
    }

这篇关于User.IsInRole()不工作角色分配后的权利,但重新登录后不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆