无法访问自定义声明

时间:2014-06-09 13:28:26

标签: asp.net-mvc-5 claims-based-identity

我正在为使用MVC5和OWIN身份验证的网站的User.Identity添加自定义声明。但我正在使用本地帐户登录。

                AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            ClaimsIdentity identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ExternalCookie);
            identity.AddClaim(new Claim("TenantID", user.TenantID.ToString())); 
            AuthenticationManager.SignIn(new AuthenticationProperties()
            {
                IsPersistent = isPersistent
            }, identity);
            return await SignInOrTwoFactor(user, isPersistent);

但是当我尝试检索回来时,我的自定义声明在该集合中不存在。这来自IdentityExtension类:

     public static short TenantID(this IIdentity identity)
    {
        if (identity == null) throw new ArgumentNullException("identity");

        var ci = identity as ClaimsIdentity;
        var value = ci != null ? ci.FindFirstValue(GlobalVariables.TenantIdIdentifier) : "0";
        return short.Parse(value);
    }

这是我的启动代码:

        public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and role manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login")
        }); }

1 个答案:

答案 0 :(得分:0)

它的工作原理如下:

                AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            ClaimsIdentity identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ExternalCookie);
            await UserManager.AddClaimAsync(user.Id, new Claim(GlobalVariables.TenantIdIdentifier, user.TenantID.ToString()));
            AuthenticationManager.SignIn(new AuthenticationProperties()
            {
                IsPersistent = isPersistent
            }, identity);
            return await SignInOrTwoFactor(user, isPersistent);