我的IUserClaimsPrincipalFactory实现导致IdentityServer4上的StackOverflowException

Has*_*san 4 asp.net-identity asp.net-core identityserver4

我使用IdentityServer4和Asp.NET Core上的Asp.NET Core Identity构建了身份服务器。我想将我的ApplicationUser的属性映射到客户端访问UserInfoEndpoint时发送的声明。

我尝试实现IUserClaimsPrincipalFactory,如下所示:

public class CustomUserClaimsPrincipalFactory : IUserClaimsPrincipalFactory<ApplicationUser>
{

    public async Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
    {
        var principal = await CreateAsync(user);
        ((ClaimsIdentity)principal.Identity).AddClaims(new[] {
        new Claim(ClaimTypes.GivenName, user.FirstName),
        new Claim(ClaimTypes.Surname, user.LastName),

         });
        return principal;
    }
}
Run Code Online (Sandbox Code Playgroud)

并像这样注册:

services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders()
                .AddClaimsPrincipalFactory<CustomUserClaimsPrincipalFactory>();
Run Code Online (Sandbox Code Playgroud)

但是当客户端尝试访问UserInfoEndpoint时,我得到了StackOverflowException。

你能帮我解决这个问题吗?

注意:我已经对其进行测试,并且在未注册ClaimsPrincipal工厂时也没有出现任何错误。

Joe*_*tte 5

这行不是递归的,函数是在无穷循环中递归地调用自身

var principal = await CreateAsync(user);
Run Code Online (Sandbox Code Playgroud)

CreateUser是您所处的函数,您再次递归调用它会创建一个无限循环,因此会导致堆栈溢出

  • 该死的。我将格式化计算机,放弃编码,然后成为时尚博客。 (16认同)