Csharp/C#教程:ASP.NET Core 2.0中缺少声明转换支持分享


ASP.NET Core 2.0中缺少声明转换支持

我在我的新asp.net核心2.0 api应用程序中使用JWT Bearer auth并希望为当前身份添加一些额外声明。 这个额外的信息位于需要查询的另一个api中。 我的理解是,索赔转换将是适当的地方。 在.net核心1.1中,您在Microsoft.AspNetCore.Authentication nuget包中有IClaimsTransformer接口,但我无法在我的.net核心2.0应用程序中安装此接口。 是否有另一种方法来转换asp.net core 2.0中的声明,这是我的用例的正确方法吗?

IClaimsTransformer已重命名为ASP.NET Core 2.0中的IClaimsTransformation

声明转换使用单个方法更简单,新的IClaimsTransformation服务:任务TransformAsync(ClaimsPrincipal principal)我们在任何成功的AuthenticateAsync调用上调用它。

 services.AddSingleton(); private class ClaimsTransformer : IClaimsTransformation { // Can consume services from DI as needed, including scoped DbContexts public ClaimsTransformer(IHttpContextAccessor httpAccessor) { } public Task TransformAsync(ClaimsPrincipal p) { p.AddIdentity(new ClaimsIdentity()); return Task.FromResult(p); } } 

请参阅https://github.com/aspnet/Security/issues/1310

还有另一种在ASP.NET Core 2.0中转换声明的方法,它还允许您访问UserStore,以便您可以检索用户的数据并将该信息添加为声明。 基本上,您编写了IUserClaimsPrincipalFactory接口的实现,并使用它在Startup.cs的ConfigureServices方法中将自定义实现添加为服务进行配置 。 Core 1.x中Core 2.0的主要变化是Identity依赖于服务的dependency injection,而不是在身份管道中使用中间件。 有一个关于创建自定义IUserClaimsPrincipalFactory以及如何在此博客文章中使用它进行授权的完整示例。

以下是创建自定义声明工厂的示例,该工厂设置用户是否为管理员的声明。

  public class MyClaimsPrincipalFactory: UserClaimsPrincipalFactory where TUser : ApplicationUser { public MyClaimsPrincipalFactory( UserManager userManager, IOptions optionsAccessor) : base(userManager, optionsAccessor) { } protected override async Task GenerateClaimsAsync(TUser user) { var id = await base.GenerateClaimsAsync(user); id.AddClaim(new Claim(MyClaimTypes.IsAdmin, user.IsAdministrator.ToString().ToLower())); return id; } } 

以下是您如何注入自定义工厂。

上述就是C#学习教程:ASP.NET Core 2.0中缺少声明转换支持分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 services.AddTransient, MyClaimsPrincipalFactory>(); 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1023090.html

(0)
上一篇 2022年1月7日
下一篇 2022年1月7日

精彩推荐