本文介绍了如何在ASP.NET Core MVC中基于用户表中的字段添加声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何基于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.

推荐答案

根据您的描述,建议您创建一个继承UserClaimsPrincipalFactory的自定义声明工厂.

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

然后,您可以将其他声明添加到重写GenerateClaimsAsync方法中.

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

更多详细信息,您可以参考以下代码:

More details, you could refer to below codes:

MyUserClaimsPrincipalFactory:

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:

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();
    }

在控制器中获取索赔:

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

结果:

这篇关于如何在ASP.NET Core MVC中基于用户表中的字段添加声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 16:45