Change Identity Role Claims Pk type as Guid

Viewed 535

I have created a datacontext with all the identity tables with Guid as primary key, but still the IdentityUserClaim and IdentityRoleClaim tables after migration are still has int as primary key. is there any way to change this to Guid as primary key

public class DataContext: IdentityDbContext<IdentityUser<Guid>, IdentityRole<Guid>, Guid, IdentityUserClaim<Guid>, IdentityUserRole<Guid>, IdentityUserLogin<Guid>, IdentityRoleClaim<Guid>, IdentityUserToken<Guid>>
{
    public DataContext(DbContextOptions<DataContext> options): base(options)
    {
            
    }
}

enter image description here

3 Answers

Customize Identity Model says:

The TKey for IdentityUserClaim is the type specified for the PK of users. In this case, TKey is string because the defaults are being used. It's not the PK type for the UserClaim entity type.

And IdentityUserClaim class looks like this:

public class IdentityUserClaim<TKey> where TKey : IEquatable<TKey>
{
    public virtual int Id { get; set; }

    public virtual TKey UserId { get; set; }

    public virtual string ClaimValue { get; set; }

    public virtual void InitializeFromClaim(Claim claim);

    public virtual Claim ToClaim();
}

It is possible to apply an update migration with EF Core on identity tables non-primary key fields such as the custom identity user table for IdentityUser. However, for a new primary key type on the ASP.NET Core Identity User, Roles, Claims tables you cannot apply an EF Core update scaffold.

A complete drop and re-create is recommended.

Apply the following:

  1. Drop the identity tables and the initial EF Core migration. This is the recommendation from Microsoft:

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/customize-identity-model?view=aspnetcore-5.0

  1. Modify the DB context class (already done).

  2. In the Startup ConfigureServices add the following to use the generic user:

    services.AddIdentity<IdentityUser>() .AddEntityFrameworkStores();

  3. Recreate the database tables from the context. This can be done using:

    context.Database.EnsureCreated();

in the Startup Configure().

It is not possible to update the primary key type of the IdentityUserClaim and IdentityRoleClaim tables. The libarary internal implementations rely on the Id column as an integer.

I guess you prefer Guids over Ints for safer security reasons. But, bear in mind that those ids are internal and should not be exposed outside of the server, so it is ok to have them as integers.

And definitely, it is recommended to change the UserId and RoleId from string to Guid as you did. Opposed to the RoleClaims and UserClaims tables, those ones are exposed to the clients and therefore, it is highly recommended they have Guids primary keys and not ints.

Related