如何根据 ASP.NET Core MVC 中用户表的字段添加声明?

Zai*_*n08 2 c# entity-framework-core asp.net-core-mvc asp.net-core

如何根据 ASP.NET Core MVC 中用户表中保存的部门名称添加声明?我有多个属于不同部门的用户。

我想根据他们的部门提出索赔。请指导我如何做到这一点。

我知道如何使用声明存储创建和编辑用户或删除用户声明,但不知道上述问题。

Bra*_*ang 5

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

\n

然后,您可以在重写GenerateClaimsAsync 方法中添加其他声明。

\n

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

\n

我的用户声明主体工厂:

\n
using IdentityTestDemo.Data;\nusing Microsoft.AspNetCore.Identity;\nusing Microsoft.Extensions.Options;\nusing System.Linq;\nusing System.Security.Claims;\nusing System.Threading.Tasks;\n\nnamespace IdentityTestDemo\n{\n    public class MyUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<IdentityUser>\n    {\n        private ApplicationDbContext _appliationDbContext;\n        public MyUserClaimsPrincipalFactory(\n        UserManager<IdentityUser> userManager,\n        IOptions<IdentityOptions> optionsAccessor,ApplicationDbContext applicationDbContext)\n            : base(userManager, optionsAccessor)\n        {\n            _appliationDbContext = applicationDbContext;\n        }\n\n        protected override async Task<ClaimsIdentity> GenerateClaimsAsync(IdentityUser user)\n        {\n           //get the data from dbcontext\n           var Iuser=   _appliationDbContext.Users.Where(x => x.EmailConfirmed == true).FirstOrDefault();\n\n            var identity = await base.GenerateClaimsAsync(user);\n            //Get the data from EF core\n\n            identity.AddClaim(new Claim("EmailTest", Iuser.Email));\n            return identity;\n        }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

启动.cs\xef\xbc\x9a

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

在控制器中获取声明:

\n
        var result = User.FindFirst("EmailTest").Value;\n
Run Code Online (Sandbox Code Playgroud)\n

结果:

\n

在此输入图像描述

\n