我创建了一个使用Identity Server 4进行Bearer Token身份验证的Asp.Net Core 2.1 Web Api。我有两个db上下文,一个用于身份验证,一个用于我的自定义应用程序的数据访问。我想在我的Web Api中使用UserManager和UserStore,并在我的控制器中使用依赖注入。
问题是,一旦我添加了DI的“相关”代码,我的控制器方法就会抛出302错误,并尝试将我重定向到登录URL。就像我的Bearer身份验证被覆盖一样。以下是我的Startup.cs的代码。你有什么想法应该如何解决吗?
public void ConfigureServices(IServiceCollection services)
{
string connectionString = Configuration.GetConnectionString("DefaultConnection");
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddDbContext<CustomContext>(options =>
options.UseSqlServer(connectionString));
// start of the stuff that should add the usermanager and userstore
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// end of the stuff
services.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters();
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://authenticate.com";
options.RequireHttpsMetadata = false;
options.ApiName = "api1";
});
services.AddCors(options =>
{
// this defines a CORS policy called "default"
options.AddPolicy("default", policy =>
{
policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
}
public void Configure(IApplicationBuilder app)
{
app.UseAuthentication();
app.UseCors("default");
app.UseMvc();
}
控制器长这样:
public class PlayerController : BaseApiController
{
private readonly UserManager<ApplicationUser> userManager;
public PlayerController(UserManager<ApplicationUser> _userManager)
{
userManager = _userManager;
}
.....
}
使用如下的BaseApiController:
[Route("api/[controller]")]
[Authorize]
public class BaseApiController : Controller
{
...
}
UserManager<T>
之外,您无需进行任何特殊操作。当您使用 Identity 时,其他所有内容都已经就位。难道您正在使用 MVC 控制器,而您的错误视图/操作需要身份验证吗?! - Tsengservices.AddIdentity()
.AddEntityFrameworkStores()
.AddDefaultTokenProviders();
一切都会按照预期进行,如果我的身份验证不再有效,我会得到 401 错误。加入“DI 代码”会导致我得到一个 302 重定向,这意味着它正在覆盖我的 Bearer 身份验证。我想添加 UserManager,而不创建另一层身份验证。 - littleowlnestAddIdentityServerAuthentication
调用。如果它们是同一个应用程序(不建议这样做),则需要按照文档将ASP.NET Core Identity与IdSrv4集成。 - Tseng