【问题标题】:Claims transformation support missing in ASP.NET Core 2.0ASP.NET Core 2.0 中缺少声明转换支持
【发布时间】:2018-01-24 08:16:57
【问题描述】:

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

【问题讨论】:

    标签: c# asp.net-core asp.net-core-2.0 claims


    【解决方案1】:

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

    索赔转换更简单,新的 IClaimsTransformation 服务具有 单一方法:Task TransformAsync(ClaimsPrincipal principal) 我们在任何成功的 AuthenticateAsync 调用上调用它。

    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

    【讨论】:

      【解决方案2】:

      在 ASP.NET Core 2.0 中还有另一种转换声明的方法,它还允许您访问 UserStore,以便您可以检索有关用户的数据并将该信息添加为声明。基本上,您编写接口 IUserClaimsPrincipalFactory 的实现并使用它进行配置,将您的自定义实现作为服务添加到 Startup.cs 的 ConfigureServices 方法中。 Core 2.0 与 Core 1.x 的主要变化是 Identity 依赖于服务的依赖注入,而不是在身份管道中使用中间件。在 blog post 中有一个关于创建自定义 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;
          }
        }
      

      以下是您注入自定义工厂的方式。

      services.AddTransient<IUserClaimsPrincipalFactory<ApplicationUser>, MyClaimsPrincipalFactory<ApplicationUser>>();
      

      【讨论】:

      • 能否详细说明如何在单点登录场景中使用IUserClaimsPrincipalFactory
      • 链接好像坏了
      • @Jota.Toledo - 该链接对我有用。当你点击它时会发生什么?
      • @Liero - 您能否详细说明 SSO 与声明转换的关系。你的用例是什么?
      • @KevinJunghans 我在 chrome 中看不到任何内容,边缘工作正常。抱歉,应该先用多个浏览器检查。
      猜你喜欢
      • 1970-01-01
      • 2016-09-11
      • 2018-01-24
      • 1970-01-01
      • 2016-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多