Zain08
Zain08

Reputation: 43

How to add claims based on the fields from users table in ASP.NET Core MVC?

How to add claim based on the name of department that is saved in users table in ASP.NET Core MVC? I have multiple users that belong to different departments.

Depending on their departments I want to create claims. Please guide me how to do this.

I know how to create and edit users or delete users claims using claims store but not the above problem.

Upvotes: 2

Views: 5285

Answers (1)

Brando Zhang
Brando Zhang

Reputation: 28322

According to your description, I suggest you could create a custom claim factory which inherits UserClaimsPrincipalFactory.

Then you could add the additional claims in the override GenerateClaimsAsync method.

More details, you could refer to below codes:

MyUserClaimsPrincipalFactory:

using IdentityTestDemo.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace IdentityTestDemo
{
    public class MyUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<IdentityUser>
    {
        private ApplicationDbContext _appliationDbContext;
        public MyUserClaimsPrincipalFactory(
        UserManager<IdentityUser> userManager,
        IOptions<IdentityOptions> optionsAccessor,ApplicationDbContext applicationDbContext)
            : base(userManager, optionsAccessor)
        {
            _appliationDbContext = applicationDbContext;
        }

        protected override async Task<ClaimsIdentity> GenerateClaimsAsync(IdentityUser user)
        {
           //get the data from dbcontext
           var Iuser=   _appliationDbContext.Users.Where(x => x.EmailConfirmed == true).FirstOrDefault();

            var identity = await base.GenerateClaimsAsync(user);
            //Get the data from EF core

            identity.AddClaim(new Claim("EmailTest", Iuser.Email));
            return identity;
        }
    }
}

Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>().AddClaimsPrincipalFactory<MyUserClaimsPrincipalFactory>(); ;
        services.AddControllersWithViews();
        services.AddRazorPages();
    }

In the controller to get the claims:

        var result = User.FindFirst("EmailTest").Value;

Result:

enter image description here

Upvotes: 5

Related Questions