1

I'm building on a couple of posts here:

So I've extended my IdentityUser with custom properties; that's all working well. These custom properties are designated in SQL Server as having default values, i.e. if I insert a new user, the default values for these custom props should just pop in, right?

No - they fail with NULL value (since they are designated with NOT NULL), and if I open them up to be not NOT NULL, they fail here (at the AddClaim line),

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
    // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
    var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

    // Add custom user claims here
    userIdentity.AddClaim(new Claim("companyId", this.companyId.ToString()));

    return userIdentity;
}

because even though the companyId default val is set in mssql = "newcompanyid", it never sets from NULL and so comes back as NULL.

What am I missing here?

3
  • 1
    "the default vals for these custom props should just pop in right" - Assuming this is all backed by an Entity Framework DbContext, then no. You have to change the mapped property to one of the StoreGeneratedPattern values - I usually change it to Identity. Commented Jun 27, 2018 at 1:51
  • 1
    Shot in the dark here but just to confirm: // Add custom user claims here userIdentity.AddClaim(new Claim("companyId", this.groupId.ToString()));... Is this meant to be group id or company id? Commented Jun 27, 2018 at 1:53
  • @Mitchell - yes except i made a type - updated now.... Commented Jun 28, 2018 at 4:27

1 Answer 1

1

thanks to tieson
i was able to fix this using this technique:

http://www.vannevel.net/2015/04/03/how-to-configure-a-custom-identityuser-for-entity-framework/

with a basis in the following:

so in the end my code looked like:

public class ApplicationUser : IdentityUser
{
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public int companyId { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

        // Add custom user claims here
        userIdentity.AddClaim(new Claim("companyId", this.companyId.ToString()));

        return userIdentity;
    }
}

hope this helps someone else

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.