You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET Core中用自定义认证服务替代默认Identity使用Identity UI?

问题描述

Microsoft.AspNetCore.Identity.UI.dll(.NET 6)自带一系列实用的身份验证页面,但现有示例都依赖默认Identity实现,比如这段VB代码:

Builder.Services.AddDefaultIdentity(Of IdentityUser)(Sub(options) options.SignIn.RequireConfirmedAccount = True).AddEntityFrameworkStores(Of ApplicationDbContext)

这种实现基于IdentityUser(可扩展为ApplicationUser)和EF数据库存储,并不适配我的项目。我已经有一个Scoped服务UserService,可以完成密码验证、获取当前用户角色等功能。

想请教以下问题:

  • 能不能不定义IdentityUser和使用EF,直接把Identity UI和自定义的UserService搭配使用?
  • 如果可以,该如何在DI容器中初始化服务以使用Identity UI,之后只调用App.UseAuthentication()和App.UseAuthorization()即可?
  • 或者Identity UI完全不适用于自定义用户认证服务?
  • 自定义用户认证服务能不能和UseAuthentication()/UseAuthorization()配合使用?
解决方案

1. Identity UI可搭配自定义UserService,无需依赖IdentityUser和EF

Identity UI本质是一套前端页面与交互逻辑,它依赖的是Identity抽象接口(如IUserStore<TUser>、IUserPasswordStore<TUser>、IRoleStore<TRole>等),而非EF这类具体实现。只要基于你的UserService实现这些必要的抽象接口,就能让Identity UI对接自定义服务。

2. DI容器初始化步骤

无需使用AddDefaultIdentity,改用AddIdentityCore注册Identity核心服务,再手动添加Identity UI,并替换默认存储实现为自定义版本:

// 注册Identity核心服务,可传入自定义用户实体(需符合接口要求)
builder.Services.AddIdentityCore<YourCustomUser>(options =>
{
    options.SignIn.RequireConfirmedAccount = true;
    // 按需配置密码规则、锁定规则等
})
// 添加Identity UI所需的页面与服务支持
.AddUI()
// 替换为自定义UserStore(基于UserService实现IUserStore等接口)
.AddUserStore<CustomUserStore>()
// 若需角色功能,添加自定义RoleStore
.AddRoleStore<CustomRoleStore>();

// 注册你的自定义UserService
builder.Services.AddScoped<IUserService, UserService>();

后续中间件配置仍只需调用:

app.UseAuthentication();
app.UseAuthorization();

核心在于实现CustomUserStore,它需要实现IUserStore<YourCustomUser>及其他Identity UI用到的接口方法,比如:

  • FindByIdAsync:通过用户ID获取用户信息
  • FindByNameAsync:通过用户名获取用户信息
  • CheckPasswordAsync:调用UserService完成密码验证
  • 若需支持注册、邮箱确认等功能,还需实现对应接口方法

3. Identity UI并非不适用于自定义认证服务

只要实现Identity要求的抽象接口,Identity UI就能正常工作。它的页面逻辑完全基于抽象层,与底层用户存储无关,因此可以适配自定义用户服务。

4. 自定义用户认证服务可与UseAuthentication/UseAuthorization配合

UseAuthentication()和UseAuthorization()是ASP.NET Core认证授权的核心中间件,依赖的是认证方案与IAuthenticationService等抽象,与具体用户存储无关。你可以:

  1. 基于UserService实现自定义认证Handler(继承AuthenticationHandler<TOptions>)
  2. 注册自定义认证方案
  3. 中间件会自动处理认证逻辑,授权环节则基于认证后的用户身份进行判断

示例注册自定义认证方案:

builder.Services.AddAuthentication("CustomScheme")
    .AddScheme<CustomAuthOptions, CustomAuthHandler>("CustomScheme", options => { });

在CustomAuthHandler中调用UserService完成身份验证,生成ClaimsPrincipal,即可让UseAuthentication识别用户身份,UseAuthorization基于角色/权限完成授权。

内容的提问来源于stack exchange,提问作者user18928007

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 03:45:39