我有 asp.net core 2.0 解决方案,其中包含以下项目:
- Data:EF代码的类库
- OAuth:作为 IdentityServer4 代码的 Web 应用程序项目
- Api:用于我创建为空 Web 项目的 API
现在OAuth项目配置了aspnetidentity并且工作正常,我能够在身份验证后获取令牌,这是它的启动代码:
public void ConfigureServices(IServiceCollection services)
{
// connect with normal database
services.AddDbContext<MCareContext>(options => options.UseSqlServer(Configuration
.GetConnectionString("MCareConnection")));
services.AddIdentity<User, IdentityRole>()
.AddEntityFrameworkStores<MCareContext>()
.AddDefaultTokenProviders();
services.AddMvc();
// IS configurations database
var dbConnectionString = Configuration.GetConnectionString("MCareConnection.OAuth");
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddIdentityServer()
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(dbConnectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
})
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(dbConnectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
})
.AddAspNetIdentity<User>()
.AddDeveloperSigningCredential();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
DatabaseInitializer.InitializeDatabase(app);
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseIdentityServer();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
现在 API 项目上的问题是,每当我打开任何授权的控制器/操作时,它都会给我 404 错误,这是启动代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MCareContext>(options => options.UseSqlServer(Configuration
.GetConnectionString("MCareConnection")));
services.AddIdentity<User, IdentityRole>()
.AddEntityFrameworkStores<MCareContext>()
.AddDefaultTokenProviders();
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:60415";
options.ApiName = "mCareApi";
options.RequireHttpsMetadata = false;
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
app.UseAuthentication();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
如果我在上面的代码中关闭这部分:
//services.AddIdentity<User, IdentityRole>()
//.AddEntityFrameworkStores<MCareContext>()
//.AddDefaultTokenProviders();
然后 Authorize 属性按预期工作,但另一个新问题是,每当我打开任何像 AccountController 这样在其构造函数上期望 UserManager userManager 的控制器时,它都会显示 500 内部服务器错误
InvalidOperationException:无法解析类型的服务
Microsoft.AspNetCore.Identity.UserManager`1[Mcare.Data.Entities.User]
尝试激活 Mcare.Api.Controllers.AccountsController 时
我想知道为什么会发生这种情况以及如何解决这个问题,而不是将 IdentityServer4 项目与 API 项目混合在一起,因为我见过的所有项目都将它们混合在一个项目中。