1. Create new field of string type in the AspNetUsers table of Identity database.

2. Add field to ApplicationUser class. (Server)

using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CustomersdbAdmin.Server.Models
{
    public class ApplicationUser : IdentityUser
    {
        public string OrgId { get; set; }
    }
}

3. Create new class called CustomUserClaimsPrincipalFactory

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using System.Security.Claims;
using Microsoft.AspNetCore.Identity;

namespace CustomersdbAdmin.Server.Models
{
    public class CustomUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser>
    {
        public CustomUserClaimsPrincipalFactory(
            UserManager<ApplicationUser> userManager,
            IOptions<IdentityOptions> optionsAccessor)
                : base(userManager, optionsAccessor)
        {
        }
        protected override async Task<ClaimsIdentity> GenerateClaimsAsync(ApplicationUser user)
        {
            var identity = await base.GenerateClaimsAsync(user);

            identity.AddClaim(new Claim("org_id", user.OrgId));

            return identity;
        }
    }
}

4. Add to ConfigureServices in Startup.cs (Server)


            services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddRoles<IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                 .AddClaimsPrincipalFactory<CustomUserClaimsPrincipalFactory>();

            services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options => {
                    options.IdentityResources["openid"].UserClaims.Add("role");
                    options.ApiResources.Single().UserClaims.Add("role");
                    options.IdentityResources["openid"].UserClaims.Add("org_id");
                    options.ApiResources.Single().UserClaims.Add("org_id");
                });

Note: As soon as the line .AddClaimsPrincipalFactory<CustomUserClaimsPrincipalFactory>(); is added, role does not work anymore.

Last modified: December 19, 2020

Author

Comments

Write a Reply or Comment