Asp.net core 使用扩展MVC核心身份用户实现自定义声明

Asp.net core 使用扩展MVC核心身份用户实现自定义声明,asp.net-core,asp.net-core-mvc,asp.net-identity,claims-based-identity,Asp.net Core,Asp.net Core Mvc,Asp.net Identity,Claims Based Identity,如何在MVC Core 2.0中创建自定义授权声明(使用AspNetCore.identity)以验证自定义用户布尔属性?我已经扩展了IdentityUser(ApplicationUser)以包含一个布尔值“IsDeveloper”。我正在使用基于声明的身份验证,并希望添加自定义声明,但不确定从何处开始。我如何创建一个自定义声明,该声明将: 查找当前(自定义)Core.Identity用户 评估自定义标识用户bool值 我理解核心身份声明,但对自定义声明不熟悉,因此我不确定从何开始。我发现的在

如何在MVC Core 2.0中创建自定义授权声明(使用AspNetCore.identity)以验证自定义用户布尔属性?我已经扩展了IdentityUser(ApplicationUser)以包含一个布尔值“IsDeveloper”。我正在使用基于声明的身份验证,并希望添加自定义声明,但不确定从何处开始。我如何创建一个自定义声明,该声明将:

  • 查找当前(自定义)Core.Identity用户
  • 评估自定义标识用户bool值
    我理解核心身份声明,但对自定义声明不熟悉,因此我不确定从何开始。我发现的在线文档不起作用或不适合我的场景。

    因此,您需要在某个地方创建自定义声明,然后通过自定义策略或手动进行检查

    1) 自定义索赔添加 JWT承载认证 您可以这样做:

    在返回jwt令牌的控制器操作中,您可以添加您的
    自定义声明

    [HttpGet]
    公共动态GetToken(字符串登录,字符串密码)
    {
    var handler=新的JwtSecurityTokenHandler();
    var sec=“1231231321231321321312313212312313213213213213213123132123132321312312312312313212313213213123123123123123132123123123121312131311”;
    var securityKey=new SymmetricSecurityKey(Encoding.UTF8.GetBytes(sec));
    var signingCredentials=新的签名凭证(securityKey、SecurityAlgorithms.HmacSha256Signature);
    var user=GetUserFromDb(登录);
    var identity=newclaimsidentity(newgenericientity(user.Email),new[]{newclaim(“user_id”,user.id)});
    if(user.IsDeveloper)
    identity.AddClaim(新声明(“IsDeveloper”、“true”));
    var token=handler.CreateJwtSecurityToken(主题:标识,
    签名凭据:签名凭据,
    观众:“示例观众”,
    发卡机构:“示例发卡机构”,
    expires:DateTime.UtcNow.AddSeconds(100));
    返回处理程序.WriteToken(令牌);
    }
    
    ASP.NET核心身份验证 您需要实现自定义的
    IUserClaimsPrincipalFactory
    或使用
    UserClaimsPrincipalFactory
    作为基类:

    公共类应用程序ClaimsIdentityFactory:Microsoft.AspNetCore.Identity.UserClaimsPrincipalFactory
    {
    用户管理器(UserManager);;
    公共应用程序LaimsIdentityFactory(UserManager用户管理器,
    IOOptions OptionAccessor):基本(用户管理器、OptionAccessor)
    {}
    公共异步覆盖任务CreateAync(ApplicationUser用户)
    {
    var principal=await base.CreateAsync(用户);
    if(user.IsDeveloper)
    {
    ((索赔实体)委托人身份)。添加索赔(新[]{
    新索赔(“IsDeveloper”、“true”)
    });
    }
    返还本金;
    }
    }
    
    然后您需要在
    启动中注册它。ConfigureServices

    services.addScope();
    
    2) 核实索赔 海关政策 在
    Startup.ConfigureServices
    中:

    services.AddAuthorization(选项=>
    {
    options.AddPolicy(“开发者”,策略=>
    policy.require(“IsDeveloper”、“true”);
    });
    
    并为开发人员保护您的行为:

    [Authorize(Policy=“Developer”),HttpGet]
    公共字符串developerCret()
    {
    返回“Hello Developer”
    }
    
    手动检查索赔 控制器中的某个位置:

    bool isDeveloper=User.Claims.Any(c=>c.Type==“isDeveloper”&c.Value==“true”)
    

    如果您使用的是其他身份验证,则想法应该是相同的。

    谢谢,ApplicationClaimsIdentityFactory是必须具备的,我只需要适应使用dotnet core 2.1,但这只是构造函数签名上的一个小改动。我建议重写
    GenerateClaimsAsync
    ,而不是
    CreateAsync
    。无需将
    principal.Identity
    转换为
    ClaimsIdentity
    然后我发现此链接对于asp.net core 2.0+非常有用: