Multi-Tenant does not cater for Role with same Role-Name in > 1

Here is what you can add to the MultiTenancyUserStore in your app to avoid this:

public override async Task AddToRoleAsync(ApplicationUser user, string normalizedRoleName, CancellationToken cancellationToken = default)
{
    if (user.NormalizedUserName.ToLower() == "tenantsadmin")
    {
        await base.AddToRoleAsync(user, normalizedRoleName, cancellationToken);
    }

    var tenant = GetTenant();
    ApplicationRole role = null;

    if (tenant != null)
    {
        role = await Context.Set<ApplicationRole>().SingleOrDefaultAsync(r => r.NormalizedName == normalizedRoleName && r.TenantId == tenant.Id, cancellationToken);
    }

    Context.Set<IdentityUserRole<string>>().Add(new IdentityUserRole<string>
    {
        RoleId = role.Id,
        UserId = user.Id
    });

    await Context.SaveChangesAsync();
}

We will add it to our templates as well.

1 Like