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

我使用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;
    }
}

并像这样注册:

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

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

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

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

参考方案

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

var principal = await CreateAsync(user);

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

ASP.NET Core Singleton实例与瞬态实例的性能 - c#

在ASP.NET Core依赖注入中,我只是想知道注册Singleton实例是否会比注册Transient实例更好地提高性能?在我看来,对于Singleton实例,创建新对象和相关对象只需花费一次时间。对于Transient实例,此成本将针对每个服务请求重复。因此Singleton似乎更好。但是,在Singleton上使用Transient时,我们可以获得多…

ASP.NET Core-在Singleton注入上存储库依赖项注入失败 - c#

我正在使用SoapCore为我的ASP.NET Core MVC应用程序创建Web服务。我正在使用Entity Framework Core和简单的存储库模式来获取我的数据库数据。我通过Startup.cs中的.AddSingleton()注入存储库类:services.AddSingleton<IImportRepository, ImportRep…

如何在ASP.NET Core Web应用程序中增加JSON反序列化MaxDepth限制 - c#

我们正在将ASP.NET Core 2.1与.NET Framework 4.6.2结合使用。我们有一个客户需要向我们的Web应用程序发送一个很大程度上嵌套的json结构。当他们进行此调用时,我们将输出以下日志并返回错误: 读取器的MaxDepth超过了32。路径“ super.long.path.to property”,第1行,位置42111。”我浏览了…

ASP.NET Core MVC视图组件搜索路径 - c#

在此处的文档中:https://docs.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-2.2 运行时在以下路径中搜索视图:/Views/{Controller Name}/Components/{View Component Name}/{View Nam…

ASP.NET MVC Core 3.0 API将枚举序列化为字符串 - c#

如何在ASP.NET MVC Core 3.0中将Enum字段序列化为String而不是Int?我不能用旧的方式做。services.AddMvc().AddJsonOptions(opts => { opts.JsonSerializerOptions.Converters.Add(new StringEnumConverter()); }) 我收到…