【问题标题】:Can't access custom claim无法访问自定义声明
【发布时间】:2014-06-09 13:28:26
【问题描述】:

我正在为使用 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")
        }); }

【问题讨论】:

  • 在索赔中存储 TenantID 是不是很危险?如果用户改变了 cookie 的值呢?
  • @Rod,你有什么建议?我只需要让这个tenantID 可以被其他函数和webapi 访问。

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


【解决方案1】:

它是这样工作的:

                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);

【讨论】:

    猜你喜欢
    • 2016-05-04
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    • 2017-09-05
    • 2020-08-19
    相关资源
    最近更新 更多