0

I am adding custom claim to the User.Identity for a web site using MVC5 and OWIN authentication. But I'm using local account sign in.

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

But when I try to retrieve back, my custom claim does not exist in the collection. This is from IdentityExtension class :

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

This is my startup code:

        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")
        }); }
Randeep Singh
  • 998
  • 2
  • 11
  • 31
  • is not dangerous store TenantID in claims? And if the user changes the value of the cookie? – Rod Mar 02 '15 at 13:46
  • @Rod, what would you suggest here? I just need to make this tenantID accessible to other functions and webapi. – Randeep Singh Mar 04 '15 at 07:04

1 Answers1

0

It works this way :

                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);
Randeep Singh
  • 998
  • 2
  • 11
  • 31