Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 385
Hasan Avatar asked Jan 07 '17 17:01

Hasan


People also ask

What is the issue number for identityserver/identityserver4?

· Issue #492 · IdentityServer/IdentityServer4 · GitHub Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community. By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

How do I add additionaluserclaimsprincipalfactory?

When creating AdditionalUserClaimsPrincipalFactory, use WebApp1User instead of ApplicationUser. Lastly, create an authz policy named IsAdmin that checks for the claim. This is a bit more involved but is covered in claims-based authz. Reframe the section as a set of tutorial steps that extend the existing tutorial.

How to demonstrate stackoverflowexception when there is an infinite recursion?

C# program to demonstrate StackOverflowException when there is an infinite recursion happening at the run time even after using try block and catch blocks of code to catch the exception. In the above program, a class called check is defined. Then a method called ex is defined which takes a value as parameter and increases its value by one.


Video Answer


1 Answers

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

like image 68
Joe Audette Avatar answered Sep 28 '22 10:09

Joe Audette