Custom RoleProvider in ASP.NET Core with Identity?

六月ゝ 毕业季﹏ 提交于 2019-12-12 12:22:41

问题


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:


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)
        }
    );
}


来源:https://stackoverflow.com/questions/35996498/custom-roleprovider-in-asp-net-core-with-identity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!