.NET 5 ASP.NET Core基于Autofac多租户从用户Claim解析租户时User未填充问题
基于.NET 5 ASP.NET Core API的多租户架构实现问题
项目背景与核心异常
我搭建了基于.NET 5的ASP.NET Core API项目,计划使用Autofac.AspNetCore.Multitenant v4.0.1实现多租户架构。目前已完成TenantIdentificationStrategy组件开发,设计逻辑为从当前用户主体的Claim中提取租户标识以完成租户识别,但遇到核心异常:Autofac执行租户标识解析逻辑的时机过早,当前请求上下文的User属性尚未被身份认证中间件填充。
查阅Autofac官方文档时看到如下明确说明:
ITenantIdentificationStrategy支持从适配应用场景的任意位置检索租户ID:环境变量、当前用户主体承载的角色、传入请求参数或其他任意适配位置。
按照文档的这段表述,我原本预期从用户主体解析租户ID的场景可以正常运行,但目前无法定位根因:不清楚是自身配置存在疏漏、框架本身存在功能缺陷,还是文档描述的能力未被框架实际支持,希望能获得该场景的可落地实现方案。
现有项目配置代码
Program 类配置
private static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseServiceProviderFactory(new AutofacMultitenantServiceProviderFactory(Startup.ConfigureMultitenantContainer)) .ConfigureWebHostDefaults(webHostBuilder => { webHostBuilder.UseStartup<Startup>(); });
Startup 类配置
public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { // [...] }); services.AddControllers(); services.AddAutofacMultitenantRequestServices(); } public void ConfigureContainer(ContainerBuilder builder) { builder.RegisterType<ClaimTenantIdentificationStrategy>() .As<ITenantIdentificationStrategy>() .SingleInstance(); builder.RegisterType<SomeService>() .As<ISomeService>() .InstancePerTenant(); } public static MultitenantContainer ConfigureMultitenantContainer(IContainer container) => new MultitenantContainer(container.Resolve<ITenantIdentificationStrategy>(), container); public void Configure(IApplicationBuilder app) { app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
TenantIdentificationStrategy 初版实现
public class ClaimTenantIdentificationStrategy : ITenantIdentificationStrategy { private readonly IHttpContextAccessor _httpContextAccessor; public ClaimTenantIdentificationStrategy(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor)); } public bool TryIdentifyTenant(out object tenantId) { tenantId = null; var claimsPrincipal = _httpContextAccessor.HttpContext?.User; var claimsIdentity = claimsPrincipal?.Identity; if (claimsIdentity != null && claimsIdentity.IsAuthenticated) { var identifier = claimsPrincipal.FindFirst("tenantId")?.Value; if (!string.IsNullOrEmpty(identifier)) tenantId = identifier; } return tenantId != null; } }
调整后的 TenantIdentificationStrategy 实现
public class ClaimTenantIdentificationStrategy : ITenantIdentificationStrategy { private readonly IHttpContextAccessor _httpContextAccessor; private readonly ITenantStore _tenantStore; public ClaimTenantIdentificationStrategy(IHttpContextAccessor httpContextAccessor, ITenantStore tenantStore) { _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor)); _tenantStore = tenantStore ?? throw new ArgumentNullException(nameof(tenantStore)); } public bool TryIdentifyTenant(out object tenantId) { var httpContext = _httpContextAccessor.HttpContext; tenantId = httpContext?.Items["TenantId"]; if (tenantId != null) return true; var authorizationHeaderValue = httpContext?.Request?.Headers?[HeaderNames.Authorization]; if (authorizationHeaderValue.HasValue && !StringValues.IsNullOrEmpty(authorizationHeaderValue.Value)) { var authorizationHeader = AuthenticationHeaderValue.Parse(authorizationHeaderValue); var jwtTokenHandler = new JwtSecurityTokenHandler(); var jwtToken = jwtTokenHandler.ReadJwtToken(authorizationHeader.Parameter); var tenantIdClaim = jwtToken.Claims .FirstOrDefault(x => x.Type == "tenantId"); if (tenantIdClaim != null && _tenantStore.IsValidTenant(tenantIdClaim.Value)) { tenantId = tenantIdClaim.Value; httpContext.Items["TenantId"] = tenantId; return true; } } return false; } }
内容的提问来源于stack exchange,提问作者GomalId
相关产品推荐
相关产品推荐

