ASP.NET Core + React无EF实现API授权遇依赖注入问题求助
问题解答
方向是否正确?
完全正确。ASP.NET Core Identity + IdentityServer的InMemory模式完全可以脱离Entity Framework实现用户认证,官方文档默认用EF是为了持久化用户/客户端数据,但开发、测试场景下用InMemory存储完全可行,也能满足基础认证需求。
报错原因与解决
你遇到的IClientRequestParametersProvider缺失问题,是因为模板中的OidcConfigurationController依赖该服务,而这个服务是由AddApiAuthorization方法注册的。如果你只手动配置了IdentityServer的InMemory选项,却没添加API授权相关服务,就会出现这个错误。
Program.cs最简配置示例
以下是不依赖EF、实现基础认证的最简配置,包含Identity、IdentityServer InMemory配置,以及API授权服务注册:
var builder = WebApplication.CreateBuilder(args); // 1. 添加Identity服务,使用InMemory存储用户(替代EF) builder.Services.AddDefaultIdentity<IdentityUser>(options => { options.SignIn.RequireConfirmedAccount = false; // 可根据需求调整密码、锁定等规则 }) .AddInMemoryUsers(); // 用InMemory用户存储,无需EF // 2. 配置IdentityServer,使用InMemory的资源、客户端 builder.Services.AddIdentityServer() .AddInMemoryIdentityResources(new List<IdentityResource> { new IdentityResources.OpenId(), // 必须的OpenID资源 new IdentityResources.Profile() // 可选的用户信息资源 }) .AddInMemoryApiScopes(new List<ApiScope> { new ApiScope("MyApi", "你的API资源名称") // 定义API范围,前端请求API时需要这个scope }) .AddInMemoryClients(new List<Client> { new Client { ClientId = "ReactApp", ClientName = "React前端应用", AllowedGrantTypes = GrantTypes.Code, // 模板默认用Authorization Code流 RequireClientSecret = false, // SPA应用无需客户端密钥 RedirectUris = { "https://localhost:5001/authentication/login-callback" }, // 对应React模板的回调地址,根据实际端口修改 PostLogoutRedirectUris = { "https://localhost:5001/authentication/logout-callback" }, AllowedScopes = { "openid", "profile", "MyApi" }, // 允许请求的范围 AllowAccessTokensViaBrowser = true // 允许在浏览器中传递AccessToken } }) .AddAspNetIdentity<IdentityUser>(); // 关联ASP.NET Core Identity // 3. 关键:添加API授权服务,注册IClientRequestParametersProvider等依赖 builder.Services.AddApiAuthorization<IdentityUser, IdentityRole>(); // 4. 添加控制器与视图服务(模板默认包含) builder.Services.AddControllersWithViews(); builder.Services.AddRazorPages(); var app = builder.Build(); // 中间件配置 if (app.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebAssemblyDebugging(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseBlazorFrameworkFiles(); app.UseStaticFiles(); app.UseRouting(); // 必须按顺序添加认证、IdentityServer、授权中间件 app.UseAuthentication(); app.UseIdentityServer(); app.UseAuthorization(); // 路由配置 app.MapRazorPages(); app.MapControllers(); app.MapFallbackToFile("index.html"); app.Run();
注意事项
- 确保React模板中的
AuthorizeService.js配置的客户端ID、scope与后端IdentityServer的客户端配置一致。 - InMemory存储的数据在应用重启后会丢失,仅适合开发测试,生产环境需要改用持久化存储(但依然可以不用EF,比如用自定义存储实现IdentityServer的接口)。
内容的提问来源于stack exchange,提问作者Julien
相关产品推荐
相关产品推荐

