创建UserClaimsPrincipalFactory
工厂
在Project.Domain
中创建ProjectUserClaimsPrincipalFactory
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Identity;
using Volo.Abp.Security.Claims;
namespace Dsh
{
[Dependency(ReplaceServices = true)]
[ExposeServices(typeof(AbpUserClaimsPrincipalFactory))] // 替换旧的AbpUserClaimsPrincipalFactory
public class DshUserClaimsPrincipalFactory : AbpUserClaimsPrincipalFactory, IScopedDependency
{
public DshUserClaimsPrincipalFactory(
UserManager<Volo.Abp.Identity.IdentityUser> userManager,
RoleManager<Volo.Abp.Identity.IdentityRole> roleManager,
IOptions<IdentityOptions> options,
ICurrentPrincipalAccessor currentPrincipalAccessor,
IAbpClaimsPrincipalFactory abpClaimsPrincipalFactory
) : base(userManager, roleManager, options, currentPrincipalAccessor, abpClaimsPrincipalFactory)
{
}
public override async Task<ClaimsPrincipal> CreateAsync(Volo.Abp.Identity.IdentityUser user)
{
var principal = await base.CreateAsync(user);
var identityPrincipal = principal.Identities.First();
identityPrincipal.AddClaim(new Claim("author", "dsh"));
return principal;
}
}
}
注意:这里使用特性自动替换服务,也可以手动替换服务
在实现了AbpModule的Module类的ConfigureServices(ServiceConfigurationContext context)方法中调用如下方法,对默认的实现进行替换
private void ConfigureCustomAuditing(ServiceConfigurationContext context)
{
// 替换一个默认实现
context.Services.Replace(ServiceDescriptor.Transient(typeof(IAuditPropertySetter), typeof(MyAuditPropertySetter)));
}
添加ApiResource,在Dsh.Domain
项目IdentityServerDataSeedContributor.cs
的CreateApiResourcesAsync
方法中,为变量commonApiUserClaims
数组添加定义的claim名称
private async Task CreateApiResourcesAsync()
{
var commonApiUserClaims = new[]
{
"email",
"email_verified",
"name",
"phone_number",
"phone_number_verified",
"role",
"author"
};
await CreateApiResourceAsync("Dsh", commonApiUserClaims);
}
然后运行 Update-Database
或着运行DbMigrator项目来更新