簡體   English   中英

ASP.NET Core中的自定義RoleProvider與身份?

[英]Custom RoleProvider in ASP.NET Core with Identity?

在過去的MVC版本中,我能夠做到

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

在web.config中獲取自定義角色提供程序,但似乎不再是這種情況。

基本上我想做的是:

  1. 用戶登錄。
  2. 成功時,從外部源獲取用戶角色。
  3. 將角色應用於用戶以在代碼中使用。
  4. 將用戶角色與自定義RoleProvider中的角色相匹配

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

如果您使用簡單的基於cookie的身份驗證而不是Identity框架,則可以將您的角色添加為聲明,並且它們將被User.IsInRole(...)[Authorize(Roles = "...")]選中[Authorize(Roles = "...")]

private async Task SignIn(string username)
{
    var claims = new List<Claim>
    {
        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)
        }
    );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM