abp icon indicating copy to clipboard operation
abp copied to clipboard

ICurrentUser

Open hikalkan opened this issue 9 years ago • 11 comments

  • Should be more and easier extensible, by extension methods?.
  • It should work by claims by default.

By default, it will only contain UserId. TenantId, Impersonator informations, organization units... should all be extensions.

hikalkan avatar Dec 25 '16 12:12 hikalkan

hi , how can I add my claims into ClaimsIdentity so I can use it from CurrentUser? I try to add "organize" below but doesn't work.

public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            var app = context.GetApplicationBuilder();

            app.UseCorrelationId();
            app.UseVirtualFiles();
            app.UseRouting();
            app.UseAuthentication();

            app.Use(async (ctx, next) =>
            {
                var currentPrincipalAccessor = ctx.RequestServices.GetRequiredService<ICurrentPrincipalAccessor>();
                var map = new Dictionary<string, string>()
                {
                    { "sub", AbpClaimTypes.UserId },
                    { "role", AbpClaimTypes.Role },
                    { "email", AbpClaimTypes.Email },
                    //any other map
                };
                var mapClaims = currentPrincipalAccessor.Principal.Claims.Where(p => map.Keys.Contains(p.Type)).ToList();
                var claimIdentity = new ClaimsIdentity(mapClaims.Select(p => new Claim(map[p.Type], p.Value, p.ValueType, p.Issuer)));
                claimIdentity.AddClaim(new Claim("organize","1111111"));
                currentPrincipalAccessor.Principal.AddIdentity(claimIdentity);
                await next();
            });
......

abllyboy avatar Jan 17 '20 10:01 abllyboy

Don't create a new Identity, but add your claims to existing Identity:

var identity = currentPrincipalAccessor.Principal?.Identities.FirstOrDefault();
if (identity != null)
{
    identity.AddClaim(...);
}

BTW, in this way you are adding the claim in every request. If that's you want, it's OK. But, we generally want to add a claim to the authentication cookie/ticker while the user is logging in. To do that;

  1. Create a class inheriting from the AbpUserClaimsPrincipalFactory class (say MyUserClaimsPrincipalFactory) and override the CreateAsync method.

  2. Find the claim value from somewhere (you can inject a service for example) and add the the ClaimsPrincipal. Do it like how AbpUserClaimsPrincipalFactory is doing it.

  3. Replace the AbpUserClaimsPrincipalFactory with your class by pre-configuring the IdentityBuilder in the PreConfigureServices of your module:

public override void PreConfigureServices(ServiceConfigurationContext context)
{
    PreConfigure<IdentityBuilder>(builder =>
    {
        builder.AddClaimsPrincipalFactory<MyUserClaimsPrincipalFactory>();
    });
}

hikalkan avatar Jan 19 '20 17:01 hikalkan

Thank you for your patience answer,I'll try this.

abllyboy avatar Jan 20 '20 04:01 abllyboy

When I create the code in your way, the class no work and breakpoints .Could you help me? the code like this:

  1. PreConfigureServices
public override void PreConfigureServices(ServiceConfigurationContext context)
        {
            
            //base.PreConfigureServices(context);

            PreConfigure<IdentityBuilder>(builder =>
            {
                builder.AddClaimsPrincipalFactory<UserClaimsPrincipalFactory>();
            });
        }
  1. override UserClaimsPrincipalFactory
public class UserClaimsPrincipalFactory : UserClaimsPrincipalFactory<IdentityUser, IdentityRole>, ITransientDependency
    {
        private readonly IRepository<IdentityUser, Guid> _identityUsers;

        public UserClaimsPrincipalFactory(
            IRepository<IdentityUser, Guid> identityUsers,
            UserManager<IdentityUser> userManager,
            RoleManager<IdentityRole> roleManager,
            IOptions<IdentityOptions> options)
            : base(
                  userManager,
                  roleManager,
                  options)
        {
            _identityUsers = identityUsers;
        }

        [UnitOfWork]
        public async override Task<ClaimsPrincipal> CreateAsync(IdentityUser user)
        {
            Console.WriteLine("-------------------------------------");
            var principal = await base.CreateAsync(user).ConfigureAwait(false);

            if (user.TenantId.HasValue)
            {
                principal.Identities
                    .First()
                    .AddClaim(new Claim(AbpClaimTypes.TenantId, user.TenantId.ToString()));
            }
            var tt = user.Claims;
            if (user.Claims != null && user.Claims.Count > 0)
            {
                foreach (var item in user.Claims)
                {
                    principal.Identities
                    .First()
                    .AddClaim(new Claim(item.ClaimType, item.ClaimValue));
                }
            }
            return principal;
            //return base.CreateAsync(user);
        }
    }

thk-liu avatar Jan 23 '20 11:01 thk-liu

@thk-liu

Your code worked for me.

image

maliming avatar Jan 24 '20 01:01 maliming

@maliming Currently I add a claim by following the ClaimsPrincipalFactory-way. How to migrate to the new AbpClaimsMapMiddleware ? I don't know where to set the value. Browsing recent middleware commit doesn't help me to answer this particular question.

Stirda avatar May 22 '20 18:05 Stirda

AbpClaimsMapMiddleware is to replace some cliams. It doesn't seem to be related to your question.

https://github.com/abpframework/abp/issues/3975

maliming avatar May 25 '20 00:05 maliming

@maliming code worked for me,but I can't get my claims from CurrentUser by this way: var allClaims = _currentUser.GetAllClaims(); or var allClaims = _currentPrincipalAccessor.Principal.Claims.ToList(); UX3HN~5@(YHGF2~5KERES S8OW} 1{U%XW9 VL58JS VH

journey191 avatar Nov 01 '20 07:11 journey191

Don't create a new Identity, but add your claims to existing Identity:

var identity = currentPrincipalAccessor.Principal?.Identities.FirstOrDefault();
if (identity != null)
{
    identity.AddClaim(...);
}

BTW, in this way you are adding the claim in every request. If that's you want, it's OK. But, we generally want to add a claim to the authentication cookie/ticker while the user is logging in. To do that;

  1. Create a class inheriting from the AbpUserClaimsPrincipalFactory class (say MyUserClaimsPrincipalFactory) and override the CreateAsync method.
  2. Find the claim value from somewhere (you can inject a service for example) and add the the ClaimsPrincipal. Do it like how AbpUserClaimsPrincipalFactory is doing it.
  3. Replace the AbpUserClaimsPrincipalFactory with your class by pre-configuring the IdentityBuilder in the PreConfigureServices of your module:
public override void PreConfigureServices(ServiceConfigurationContext context)
{
    PreConfigure<IdentityBuilder>(builder =>
    {
        builder.AddClaimsPrincipalFactory<MyUserClaimsPrincipalFactory>();
    });
}

How to achieve the same result in v4.2.2. I am using microservices. Also added the module to the authserver project. The code is not getting executed on login.

public class ResellerUserClaimsPrincipalFactory : AbpUserClaimsPrincipalFactory
    {
        public ResellerUserClaimsPrincipalFactory(
           UserManager<IdentityUser> userManager,
           RoleManager<IdentityRole> roleManager,
           IOptions<IdentityOptions> options, ICurrentPrincipalAccessor currentPrincipalAccessor,
            IAbpClaimsPrincipalFactory abpClaimsPrincipalFactory)
           : base(
                 userManager,
                 roleManager,
                 options, currentPrincipalAccessor, abpClaimsPrincipalFactory)
        {
        }


        [UnitOfWork]
        public async override Task<ClaimsPrincipal> CreateAsync(IdentityUser user)
        {
            var principal = await base.CreateAsync(user);
            var identity = principal.Identities.First();

            if (user.GetResellerId() != Guid.Empty)
            {
                identity.AddIfNotContains(new Claim("ResellerId", user.GetResellerId().ToString()));
            }

            return principal;

        }
    }

Added to the preconfigure services of the module.

public override void PreConfigureServices(ServiceConfigurationContext context)
        {
            PreConfigure<IdentityBuilder>(builder =>
            {
                builder.AddClaimsPrincipalFactory<ResellerUserClaimsPrincipalFactory>();
            });
        }

piresashwin avatar Apr 07 '21 11:04 piresashwin

I'm following this procedure but I'm doing it

var principal = await base.CreateAsync(user).ConfigureAwait(false);

It reported The error System. InvalidOperationException: "The navigation 'IdentityUser. Claims' always be The loaded because The entity is not being tracked. Navigations can only be loaded for tracked entities.”

lijiaxuanabc avatar Nov 28 '23 07:11 lijiaxuanabc

@thk-liu

Your code worked for me.

image

i have the same Problem , can you share the full code that is working for you , i dont understand what is the problem this is my code using System.Linq; using System; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; using Volo.Abp.Identity; using Volo.Abp.Security.Claims; using Volo.Abp.Uow; using Volo.Abp.DependencyInjection; using IdentityUser = Volo.Abp.Identity.IdentityUser; using IdentityRole = Volo.Abp.Identity.IdentityRole;

namespace NozhanPlatform { public class MyUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<IdentityUser, IdentityRole>, IScopedDependency { public MyUserClaimsPrincipalFactory( UserManager userManager, RoleManager roleManager, IOptions options) : base( userManager, roleManager, options) { }

    [UnitOfWork]
    public override async Task<ClaimsPrincipal> CreateAsync(IdentityUser user)
    {
        Console.WriteLine("oooooo!");

        var principal = await base.CreateAsync(user).ConfigureAwait(false);

        if (user.TenantId.HasValue)
        {
            principal.Identities
                .First()
                .AddClaim(new Claim(AbpClaimTypes.TenantId, user.TenantId.ToString()));
        }

        return principal;
    }
}

} public override void PreConfigureServices(ServiceConfigurationContext context) {

  var hostingEnvironment = context.Services.GetHostingEnvironment();
  var configuration = context.Services.GetConfiguration();


  PreConfigure<IdentityBuilder>(builder =>
  {
      builder.AddClaimsPrincipalFactory<MyUserClaimsPrincipalFactory>();
  });

  PreConfigure<OpenIddictBuilder>(builder =>
  {
      builder.AddValidation(options =>
      {
          options.AddAudiences("NozhanPlatform");
          options.UseLocalServer();
          options.UseAspNetCore();
      });
  });

MehtiSini avatar Oct 23 '24 08:10 MehtiSini