用户数据库“UserDbWebApi”上有一个单独的 WebApi 项目,项目使用该项目对IdentityServer4 “IdentityServerApi_AspNetIdentity”进行授权。
要为“UserDbWebApi”提供 CRUD 操作,还需要通过 IdentityServer4 进行注册(只有具有 SuperAdmin 角色的用户才能访问此 api)。ApplicationUser用户以继承自 IdentityUser (ASP.NET Core Identity)的便捷方式存储。问题是认证ASP.NET Core Identity系统覆盖了认证系统IdentityServer4。
为了方便使用用户数据库,ASP.NET Core Identity建议在 EF 上使用方便的服务:
UserManager<ApplicationUser>
RoleManager<ApplicationUser>
要在 DI 中注册它们,您需要连接
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
然后在整个项目中通过 DI 提供这些服务。
但是该调用AddIdentity还将授权ASP.NET Core Identity和访问与颁发的令牌连接起来IdentityServer4不再起作用。
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
[Authorize(Roles = "SuperAdmin")]
public ActionResult<IEnumerable<string>> Get()
{
//Доступ работает только с токеном выданным IdentityServer4
}
}
因此,对于授权的正常操作AddIdentity,我不需要连接,但我需要服务UserManager,RoleManager。如何注册DI?在额头不起作用
services.AddScoped<UserManager<ApplicationUser>>();
services.AddScoped<RoleManager<ApplicationUser>>();
或者如何使用禁用授权AddIdentity?
还是您仍然必须放弃 UserManager、RoleManager 并直接使用 EF 上下文?
您必须在属性中明确指定授权系统。将 Cookie 用于 AspNetIdentity 或将 Bearer 用于我通过颁发的令牌进行授权的情况。[Authorize(AuthenticationSchemes = "Bearer", Roles = "SuperAdmin")] 就是这样!并且您可以连接 AddIdentity 服务。