Claims transformation support missing in ASP.NET Core 2.0

后端 未结 2 928
[愿得一人]
[愿得一人] 2020-12-31 10:21

I am using JWT Bearer auth in my new asp.net core 2.0 api app and want to add some extra claims to the current identity. This extra info is located in another api which need

2条回答
  •  无人及你
    2020-12-31 10:52

    There is another method for transforming claims in ASP.NET Core 2.0 which also gives you access to the UserStore so you can retrieve data on the user and add that information as claims. Basically you write an implementation of the interface IUserClaimsPrincipalFactory and configure using it adding your custom implementation as a service in the ConfigureServices method in Startup.cs. The main changes in Core 2.0 from Core 1.x is that Identity relies on dependency injection of services instead of using middleware in the identity pipeline. There is a complete example on creating a custom IUserClaimsPrincipalFactory and how to use it for authorization in this blog post.

    Here is an example of creating a custom claims factory that sets a claim for whether the user is an administrator or not.

        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;
        }
      }
    

    And here is how you inject the custom factory.

    services.AddTransient, MyClaimsPrincipalFactory>();
    

提交回复
热议问题