Custom RoleProvider in ASP.NET Core with Identity?

2019-06-26 12:55发布

In past MVC versions I was able to do

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

in to the web.config to get a custom role provider, but that doesn't seem to be the case anymore.

Essentially what I want to do is:

  1. The user logs in.
  2. On success, get roles for user from external source.
  3. Apply roles to user to be used in code.
  4. Match user roles to roles in custom RoleProvider

How do I do this in ASP.NET Core?

1条回答
成全新的幸福
2楼-- · 2019-06-26 13:46

If you're using simple cookie-based authentication instead of the Identity framework, you can add your roles as claims and they will be picked up by User.IsInRole(...), [Authorize(Roles = "...")], etc.

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)
        }
    );
}
查看更多
登录 后发表回答