我的IUserClaimsPrincipalFactory实现在IdentityServer4上引起了StackOverflowException异常。

8

我使用IdentityServer4和Asp.NET Core Identity在Asp.NET Core上构建了一个身份验证服务器。我希望将我的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;
    }
}

然后像这样注册它:

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

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

你能帮我修复一下吗?

注意:我测试过,如果不注册ClaimsPrincipal工厂,就不会出现任何错误。


3
var principal = await CreateAsync(user); 这里你正在递归调用该方法直到堆栈溢出。 你可能想要调用一些不同的东西,比如UserManager或Repository? (译者注:原文中的“calling something different”意为“调用其他方法”,并没有指具体的方法名称) - Tseng
2个回答

9

这行代码不是递归吗?函数在一个无限循环中调用自身。

var principal = await CreateAsync(user);

CreateUser是你正在使用的函数,你在其中递归调用它,导致无限循环,从而出现堆栈溢出


33
该死。我要格式化我的电脑,放弃编程,成为一名时尚博主。 - Hasan

4

首先,更改这行代码

public class CustomUserClaimsPrincipalFactory : IUserClaimsPrincipalFactory<ApplicationUser>

to

public class CustomUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser,IdentityRole>

然后,更改这行。
var principal = await CreateAsync(user);

 var principal = await base.CreateAsync(user);

                 

当仅实现一个接口时,就没有所谓的“base”。这个方法必须由开发人员完全定义。 - Mike Guthrie
1
你是对的 @MikeGuthrie。 这一行代码 public class CustomUserClaimsPrincipalFactory : IUserClaimsPrincipalFactory<ApplicationUser> 需要修改为 public class CustomUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser,IdentityRole> - Pieter van Kampen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接