c# - 我的 IUserClaimsPrincipalFactory 实现导致 IdentityServer4 上出现 StackOverflowException

标签 c# asp.net-core asp.net-identity identityserver4

我在 Asp.NET Core 上使用 IdentityServer4 和 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;
    }
}

并像这样注册:

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

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

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

注意:我测试了它,当我不注册 ClaimsPrincipal 工厂时,我没有收到任何错误。

最佳答案

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

var principal = await CreateAsync(user);

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

关于c# - 我的 IUserClaimsPrincipalFactory 实现导致 IdentityServer4 上出现 StackOverflowException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41524313/

相关文章:

c# - 你如何编辑一个用户,谁的电子邮件用户名包含一个连字符?

c# - 您如何手动设置登录身份用户?

c# - 如何在一段时间后强行关闭c#中的进程?

c# - 在 C# 中将时间转换为十进制

c# - 从 EPiServer 的 PageFiles 文件夹中获取目录

c# - 读取 Main Program.cs 中的 appsettings.json

c# - 从 Core 2.0 更新到 3.1.1 后响应正文为空

SPListItemCollection 上的 C# Parallel.ForEach() 导致异常 (0x80010102)

c# - 从数据库加载 ASP.Net Core 授权策略

C# Azure 身份验证和身份