Search code examples
c#asp.net-coreasp.net-identityidentityserver4

My IUserClaimsPrincipalFactory implementation is causing StackOverflowException on IdentityServer4


I built an identity server using IdentityServer4 with Asp.NET Core Identity on Asp.NET Core. I want to map my ApplicationUser's properties to the claims sent when a client accesses UserInfoEndpoint.

I tried to implement IUserClaimsPrincipalFactory as follows:

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

and register it like:

services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders()
                .AddClaimsPrincipalFactory<CustomUserClaimsPrincipalFactory>();

but I am getting StackOverflowException when the client tries to access the UserInfoEndpoint.

Can you please help me fix this?

Note: I tested it and I don't get any errors when I don't register the ClaimsPrincipal factory.


Solution

  • isn't this line recursive, the function is calling itself recursively in an endless loop

    var principal = await CreateAsync(user);
    

    CreateUser is the function you are in and you call it again recursively which creates an infinite loop, hence stack overflow