首页 > 编程语言 >Customising claims transformation in ASP.NET Core Identity

Customising claims transformation in ASP.NET Core Identity

时间:2023-05-09 16:12:48浏览次数:55  
标签:Core ASP user new Customising claims public Identity principal

I’ve been testing out the new version of ASP.NET Identity and had the need to include additional claims in the ClaimIdentity generated when a user is authenticated.

Transforming Claims Identity

ASP.NET Core supports Claims Transformation out of the box. Just create a class that implements IClaimsTransformer:

public class ClaimsTransformer : IClaimsTransformer
{
    public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        ((ClaimsIdentity)principal.Identity).AddClaim(new Claim("ProjectReader", "true"));
        return Task.FromResult(principal);
    }
}

To register the claims transformer, add the following inside your Configure method in Startup.cs:

app.UseClaimsTransformation(new ClaimsTransformationOptions
{
    Transformer = new ClaimsTransformer()
});

One problem with the current implementation of the claims transformation middleware is that claims transformer instances have to be created during configuration. This means no DI making it difficult to handle loading claim information from a database.

Note: I’m told this will be fixed in RC2.

Claims Identity Creation

In my application I’d extended the default ApplicationUser class with additional properties for first and last name. I wanted these properties to be included in the generated ClaimsIdentity:

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

ASP.NET Core Identity has a SignInManager<TUser> responsible for signing users into your application. Internally it uses a IUserClaimsPrincipalFactory<TUser> to generate a ClaimsPrincipal from your user.

The default implementation only includes username and user identifier claims. To add additional claims we can create our own implementation of IUserClaimsPrincipalFactory<TUser> or derive from the default UserClaimsPrincipalFactory:

public class AppClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>
{
    public AppClaimsPrincipalFactory(
        UserManager<ApplicationUser> userManager,
        RoleManager<IdentityRole> roleManager,
        IOptions<IdentityOptions> optionsAccessor) : base(userManager, roleManager, optionsAccessor)
    {
    }

    public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
    {
        var principal = await base.CreateAsync(user);

        ((ClaimsIdentity)principal.Identity).AddClaims(new[] {
            new Claim(ClaimTypes.GivenName, user.FirstName),
            new Claim(ClaimTypes.Surname, user.LastName),
        });

        return principal;
    }
}

To register the custom factory we add the following to the ConfigureServices method in startup.cs after the services.AddIdentity() call:

services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, AppClaimsPrincipalFactory>();
    转 https://benfoster.io/blog/customising-claims-transformation-in-aspnet-core-identity/   参考 https://learn.microsoft.com/en-us/answers/questions/1009750/how-to-add-custom-claims-on-user-identity-net-6

标签:Core,ASP,user,new,Customising,claims,public,Identity,principal
From: https://www.cnblogs.com/wl-blog/p/17385417.html

相关文章

  • 【asp.net core】自定义模型绑定及其验证
    引言水此篇博客,依旧是来自群里的讨论,最后说到了,在方法参数自定义了一个特性,用来绑定模型,优先从Form取,如果为空,或者不存在,在从QueryString中获取并且绑定,然后闲着无聊,就水一篇博客,如果大家有什么需求或者问题,可以找我,很高兴能为你们带来帮助。IModelBinderFactory......
  • 【HMS Core】Health Kit想要查看数据是来自用户的哪个设备,如何查看?
     【问题描述1】如何查看运动健康数据是来自用户的哪个设备?【解决方案】可以通过返回的数据中携带的dataCollectorId来查询提供数据的设备信息:请求示例(以查询睡眠记录详情为例):1、查询睡眠记录并关联睡眠状态采样数据:​2、根据关联采样数据返回的dataCollectorId调用查询指......
  • 使用 Ef core 时 报错Data is Null. This method or property cannot be called on
    1.问题在使用EFcore做查询操作的时候报错"DataisNull.ThismethodorpropertycannotbecalledonNullvalues.”"2.解决这是数据库中的某个属性为空导致,即使这个属性srting类型,也需要将字段标记为可空的......
  • kali Metasploit导入模块
    比如对于漏洞CyberLinkLabelPrint2.5-StackBufferOverflow(Metasploit)-WindowslocalExploit(exploit-db.com)首先从Exploit-DB下载45985.rb文件,该文件是ruby写的metasploit模块,用来复现攻击将模块复制到metasploit的渗透攻击模块目录cd/usr/share/metasploit-fr......
  • mac版DataSpell2023:专业数据科学家的 IDE,macbook程序员必备
    DataSpell2023forMac是一款强大的数据科学工具,它提供了广泛的功能和工具,帮助用户更好地分析、处理和可视化数据。无论是数据分析师、数据科学家、商业分析师还是研究人员,DataSpellforMac都是一个理想的选择。mac软件下载:https://mac.macsc.com/mac/4116.html?id=MzI1OTY2......
  • C# .net core 返回json 中文字符编码被转换或乱码问题
    开发环境VS2022+.NET6.0现象接口返回Json中文数据时出现乱码。例如后台返回结果:"0506133015\u56FE\u8868\u9009\u62E9.png"。解决办法以下方法任选其一即可。//方法1:在Program.cs中添加以下代码varbuilder=WebApplication.CreateBuilder(args);builder.Services.Ad......
  • How to use Linux command or Python code get Raspberry PI's Temperature All In On
    HowtouseLinuxcommandorPythoncodegetRaspberryPI'sTemperatureAllInOne如何使用Linux命令或Python代码获取RaspberryPI的温度raspberrypicheckthetemperatureimportgpiozeroasgz#readthetemperatureintoavariable:cpu_temp=gz.CPUTe......
  • How to connect to multiple SSD1306 OLED Displays using Raspberry Pi GPIO I2C PIN
    HowtoconnecttomultipleSSD1306OLEDDisplaysusingRaspberryPiGPIOI2CPINAllInOne如何使用RaspberryPi的GPIOI2CPIN连接多个SSD1306OLED显示器demos(......
  • 若依--自定义指令 v-hasPermi 和 v-hasRole
    为什么大家都在用若依?若依版本有很多种,前端的,后端的,大家点击去看看http://doc.ruoyi.vip/,看完记得回来!第一次接触到若依是进入这家公司之后,以前做项目都是“白手起家”,若依项目结构清晰,很多轮子都被造好了,不用自己搭建项目,gitclone就完成了,happy!还有项目文档可以查看,虽然我......
  • 【Dotnet 工具箱】DotNetCorePlugins- 动态加载和卸载 .NET 程序插件
    你好,这里是Dotnet工具箱,定期分享Dotnet有趣,实用的工具和组件,希望对您有用!1.DotNetCorePlugins-动态加载和卸载.NET程序插件DotNetCorePlugins是一个.NET的开源插件项目,它提供了能够动态加载程序集的API,然后把它们作为.NET主程序的扩展程序执行。这个库主要用到了......