将自定义用户模型与 .NET 8 Identity API 端点结合使用

问题描述 投票:0回答:1

我正在我的 asp .net core api 项目中使用新的身份 API 端点,但我想为应用程序用户使用更多自定义属性。 我的用户类别如下所示:

public class ApplicationUser : IdentityUser
{
    [StringLength(256)]
    public string? Name { get; set; }
    [StringLength(256)]
    public string? Surname { get; set; }

    /// <summary>
    /// Years and fraction of year of experience on drums
    /// </summary>
    public float Experience { get; set; }
}

身份配置:

public static IServiceCollection ConfigureIdentity(this IServiceCollection services, IConfiguration configuration)
{
    var connectionString= configuration.GetConnectionString("IdentityConnection");
    //Guard.Against.Null(connectionString, $"Connection string for 'IdentityConnection' not found");

    services.AddDbContext<AppIdentityDbContext>((sp, options) =>
    {
        options.UseSqlite("DataSource=app.db");
    });

    services.AddScoped<IApplicationDbContext>(provider => provider.GetRequiredService<AppIdentityDbContext>());

    services.AddScoped<AppIdentityDbContextInitializer>();

    services.AddIdentityApiEndpoints<ApplicationUser>()
        .AddRoles<IdentityRole>()    
        .AddEntityFrameworkStores<AppIdentityDbContext>();

    services.AddAuthorizationBuilder();
    services.AddTransient<IIdentityService, IdentityService>();

    services.AddAuthorizationBuilder()
        .AddPolicy(Policies.CanAddHomework, policy => policy.RequireRole(Roles.Teacher));

    return services;
}

在API程序类中:

app.MapIdentityApi<ApplicationUser>();

数据库是使用自定义属性创建的,但在使用注册端点时,我只能传递电子邮件和密码,无论我在请求正文中发送了什么。我什至无法设置 IdentityUser 类中的默认属性用户名。用户名始终是电子邮件。 是否有任何选项可以配置注册端点以接受自定义正文,或者我需要摆脱身份 API 端点并使用旧身份实现身份验证?

c# asp.net .net asp.net-identity asp.net-core-webapi
1个回答
0
投票

ASP.NET Core Identity 提供的 Identity API 端点设计得很灵活,允许您编辑内容,但它们确实有一定的限制,特别是在注册过程中。默认情况下,注册端点需要用户名和密码,这种行为在身份系统的工作方式中根深蒂固。您可能需要实现自己的注册逻辑才能处理自定义属性。以下是如何实现此目的的基本概述:

  1. 创建一个类来表示您想要在 注册请求。

    
    
    public class RegistrationDto
    {
        public string Email { get; set; }
        public string Password { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
        public float Experience { get; set; }
    }
    
  2. 创建一个新端点或修改现有端点来处理 注册逻辑。

     [API控制器]
        [路线(“api/帐户”)]
        公共类 AccountController : ControllerBase
        {
            私有只读 UserManager _userManager;
            公共AccountController(UserManager userManager)
            {
                _userManager = 用户管理器;
            }
            [HttpPost(“注册”)]
            公共异步任务注册([FromBody] RegistrationDto 模型)
            {
                if (!ModelState.IsValid)
                {
                    返回 BadRequest(ModelState);
                }
                var user = 新的应用程序用户
                {
                    用户名 = 型号.电子邮件,
                    电子邮件 = 型号.电子邮件,
                    名称 = 型号.名称,
                    姓氏 = 模特.姓氏,
                    经验=模型.经验
                };
                var result = wait _userManager.CreateAsync(用户, model.Password);
                if (结果.成功)
                {
                    // 如果注册成功则附加逻辑
                    return Ok(new { Message = "注册成功。" });
                }
                // 注册失败
                return BadRequest(new { Message = "注册失败。", Errors = result.Errors });
            }
        }
    
  3. 确保您的应用程序的服务配置正确。 您可能需要修改 Startup.cs 中的注册过程 文件。

     服务.AddIdentity()
            .AddEntityFrameworkStores()
            .AddDefaultTokenProviders();
        服务.配置(选项=>
        {
            // 根据需要配置身份选项
        });
        // 其他服务配置...
    
  4. 如果您使用客户端应用程序来注册用户,请更新 包含附加属性的注册请求。

     {
            "email": "[电子邮件受保护]",
            “密码”:“myP@s5w0rd”,
            “姓名”:“乔治”,
            “姓”:“斯米尔利斯”,
            “经验”:6.5
        }
    

这是一个基本的例子,我可以想象它可以帮助你。

© www.soinside.com 2019 - 2024. All rights reserved.