ter*_*tyl 7 c# claims asp.net-core asp.net-core-2.0
我在我的新asp.net core 2.0 api应用程序中使用JWT Bearer auth,并希望为当前身份添加一些额外的声明.这个额外的信息位于需要查询的另一个api中.我的理解是,索赔转换将是适当的地方.在.net核心1.1中,您在Microsoft.AspNetCore.Authentication nuget包中有IClaimsTransformer接口,但我无法在我的.net核心2.0应用程序中安装此接口.是否有另一种方法来转换asp.net core 2.0中的声明,这是我的用例的正确方法吗?
Can*_*Wan 17
IClaimsTransformer
已IClaimsTransformation
在ASP.NET Core 2.0中重命名为.
声明转换使用单个方法更简单,新的IClaimsTransformation服务:任务TransformAsync(ClaimsPrincipal principal)我们在任何成功的AuthenticateAsync调用上调用它.
Run Code Online (Sandbox Code Playgroud)services.AddSingleton<IClaimsTransformation, ClaimsTransformer>(); private class ClaimsTransformer : IClaimsTransformation { // Can consume services from DI as needed, including scoped DbContexts public ClaimsTransformer(IHttpContextAccessor httpAccessor) { } public Task<ClaimsPrincipal> 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依赖于服务的依赖注入,而不是在身份管道中使用中间件.有一个关于创建自定义IUserClaimsPrincipalFactory以及如何在此博客文章中使用它进行授权的完整示例.
以下是创建自定义声明工厂的示例,该工厂设置用户是否为管理员的声明.
public class MyClaimsPrincipalFactory<TUser>: UserClaimsPrincipalFactory<TUser> where TUser : ApplicationUser
{
public MyClaimsPrincipalFactory(
UserManager<TUser> userManager,
IOptions<IdentityOptions> optionsAccessor) : base(userManager,
optionsAccessor)
{
}
protected override async Task<ClaimsIdentity> GenerateClaimsAsync(TUser user)
{
var id = await base.GenerateClaimsAsync(user);
id.AddClaim(new Claim(MyClaimTypes.IsAdmin, user.IsAdministrator.ToString().ToLower()));
return id;
}
}
Run Code Online (Sandbox Code Playgroud)
以下是注入定制工厂的方法.
services.AddTransient<IUserClaimsPrincipalFactory<ApplicationUser>, MyClaimsPrincipalFactory<ApplicationUser>>();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7113 次 |
最近记录: |