ICurrentUser
- 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.
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();
});
......
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;
-
Create a class inheriting from the
AbpUserClaimsPrincipalFactoryclass (say MyUserClaimsPrincipalFactory) and override the CreateAsync method. -
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.
-
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>();
});
}
Thank you for your patience answer,I'll try this.
When I create the code in your way, the class no work and breakpoints .Could you help me? the code like this:
- PreConfigureServices
public override void PreConfigureServices(ServiceConfigurationContext context)
{
//base.PreConfigureServices(context);
PreConfigure<IdentityBuilder>(builder =>
{
builder.AddClaimsPrincipalFactory<UserClaimsPrincipalFactory>();
});
}
- 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
Your code worked for me.

@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.
AbpClaimsMapMiddleware is to replace some cliams. It doesn't seem to be related to your question.
https://github.com/abpframework/abp/issues/3975
@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();

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;
- Create a class inheriting from the
AbpUserClaimsPrincipalFactoryclass (say MyUserClaimsPrincipalFactory) and override the CreateAsync method.- 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.
- 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>();
});
}
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.”
@thk-liu
Your code worked for me.
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
[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();
});
});