ASP.NET核心中的自定义RoleProvider与身份?

在过去的MVC版本中,我能够做到

<roleManager enabled="true" defaultProvider="...." ... 

在web.config中获取自定义角色提供程序,但似乎不再是这种情况。

基本上我想做的是:

  1. 用户登录。
  2. 成功时,从外部源获取用户角色。
  3. 将角色应用于用户以在代码中使用。
  4. 将用户角色与自定义RoleProvider中的角色相匹配

我如何在ASP.NET Core中执行此操作?

如果您使用简单的基于cookie的身份validation而不是Identity框架,则可以将您的角色添加为声明,并且它们将被User.IsInRole(...)[Authorize(Roles = "...")]选中[Authorize(Roles = "...")]

 private async Task SignIn(string username) { var claims = new List { new Claim(ClaimTypes.Name, username) }; // TODO: get roles from external source claims.Add(new Claim(ClaimTypes.Role, "Admin")); claims.Add(new Claim(ClaimTypes.Role, "Moderator")); var identity = new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role ); await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTime.UtcNow.AddMonths(1) } ); }