所以我一直在为这个问题痛心疾首。
我们有一个 Web 应用程序正在使用 IdentityServer4 和 AspNetIdentity 验证和注册用户(这是按预期工作的)。
此外,我们还有其他 API(在同一解决方案中)能够使用 IdentityServer4 对访问 API 的用户进行身份验证 .
然而,问题是,除了身份验证,我们不能使用 API 到 创建新用户 .
例如,用户应该能够通过 Web API 而不仅仅是从 Web 应用程序创建其他用户,因为在我们的例子中,用户链接到其他用户(将其视为多个配置文件)。
我不太熟悉 .Net Core 框架提供的所有配置服务,我尝试了多种通过 API 访问 Web 应用程序的用户管理器以通过经典 POST 请求注册我的用户的方法,但似乎没有任何效果.在线搜索很棘手,因为我们的问题非常具体,这就是我在这里发帖的原因。
API Startup.cs - 配置服务:
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
// base-address of your identityserver
options.Authority = Configuration["IdentityServer:Url"];
// name of the API resource
options.ApiName = Configuration["IdentityServer:APIName"];
options.ApiSecret = Configuration["IdentityServer:APISecret"];
options.EnableCaching = true;
options.CacheDuration = TimeSpan.FromMinutes(10); // that's the default
options.RequireHttpsMetadata = Convert.ToBoolean(Configuration["IdentityServer:RequireHttpsMetadata"]);
});
API Startup.cs - 配置:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("AllowAllOrigins");
app.UseAuthentication();
app.UseMvc();
}
API UsersController.cs - 构造函数:
private readonly UserManager<ApplicationUser> _userManager;
private readonly ApplicationDbContext _context;
public UsersController(IUserService service,
ApplicationDbContext context,
UserManager<ApplicationUser> userManager)
{
_service = service;
_userManager = userManager;
_context = context;
}
现在的问题是,当我启动 API 并尝试访问 UsersController 时,出现以下错误:
System.InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[XXXXX.Data.Models.ApplicationUser]' while attempting to activate 'XXXXXXX.Api.Controllers.UsersController'.
我真诚地希望我至少能找到一些关于如何进行的建议。
如果有什么不清楚的地方请回复,我会很乐意添加更多信息或把事情说清楚。
亲切的问候,
马里奥。
编辑:
谢谢大家的回复。 @Vidmantas 下面提供的代码片段做到了。
由于我对 .net core 的了解有限,我在配置服务功能中做了很多尝试和错误,正如您想象的那样,但没有奏效。我坚信使用 .net core 有点容易(例如 API),但是当涉及到配置服务时,复杂性(主要是令人费解/令人困惑)会爆炸。
至于架构,你给了我 future 重构的好主意。记笔记。
马里奥。
最佳答案
如果我对您的理解正确,那么您实际上不应该通过 API 创建用户——这就是您安装 Identity Server 4 的原因——为您的用户群提供中央授权进行身份验证。你真正需要的是:
如果你选择最后一个选项,那么你可能需要像下面这样添加:
services.AddDbContext<IdentityContext>(); //make sure it's same database as IdentityServer4
services.AddIdentityCore<ApplicationUser>(options => { });
new IdentityBuilder(typeof(ApplicationUser), typeof(IdentityRole), services)
.AddRoleManager<RoleManager<IdentityRole>>()
.AddSignInManager<SignInManager<ApplicationUser>>()
.AddEntityFrameworkStores<IdentityContext>();
这将为您提供足够的服务来使用
UserManager
它不会设置任何不必要的身份验证方案。由于关注点分离,我不推荐最后一种方法 - 您的 API 应该关注提供资源,而不是创建用户和提供资源。在我看来,第一种和第二种方法没问题,但我总是倾向于为 AspNetIdentity 管理提供干净的单独服务。
我的一个项目中的示例架构,我们在其中实现了这种方法:
关于c# - 使用 IdentityServer4 从多个 API 创建用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54493921/