Search code examples
c#authenticationasp.net-identityidentityserver4asp.net-core-2.0

IdentityUser Does not Contain Definition for Claim Migration


Today, I made the frustrating decision to upgrade to .Net-Core 2.0 for Identity Server 4 (Not like I really had much of a choice).

In my old application I was adding in a Test in memory user as a default login for testing. This used the Identity Server 4 Tutorial code, Which looked like this:

if (!userManager.Users.Any())
{
    foreach (var inMemoryUser in Users.Get())
    {
        var identityUser = new IdentityUser(inMemoryUser.Username)
        {
            Id = inMemoryUser.SubjectId
        };

        foreach (var claim in inMemoryUser.Claims)
        {
            identityUser.Claims.Add(new IdentityUserClaim<string>
            {
                UserId = identityUser.Id,
                ClaimType = claim.Type,
                ClaimValue = claim.Value,
            });
        }

        userManager.CreateAsync(identityUser, "Password123!").Wait();
    }
}

I am receiving an error:

IdentityUser does not contain a definition for claims

I'm aware that this was a breaking change from as you can see in the breaking change announcement

    /// <summary>
    /// Navigation property for the roles this user belongs to.
    /// </summary>
    public virtual ICollection<TUserRole> Roles { get; } = new List<TUserRole>();

    /// <summary>
    /// Navigation property for the claims this user possesses.
    /// </summary>
    public virtual ICollection<TUserClaim> Claims { get; } = new List<TUserClaim>();

    /// <summary>
    /// Navigation property for this users login accounts.
    /// </summary>
    public virtual ICollection<TUserLogin> Logins { get; } = new List<TUserLogin>();

If you were using these navigation properties, you will need to add them back to your application specific user class

What does this mean, I do not have an application specific user class?

My Identity registrations is like so:

services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();

How am I suppose to fix this, Am I suppose to create a custom IdentityUser class and add (Claims, Roles, Logins)properties?
I don't see how that could help, being that they do not use a common interface, how could they ever be repopulated again? Are they using duck-typing and my assumption is correct?


Solution

  • To get your Code running again, you need to:

    Customize your Application User-Class ( this means extend the IdentityUser with the Navigation-Properties); Then use your User-class in your IdentityContext (as Generic-Parameter) and finally migrate your Database if it’s not done yet. Then everything should be running again.