Custom RoleProvider in ASP.NET core with authentication?

In previous versions of MVC, I was able to do

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

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

Essentially, I want:

  • The user is logged in.
  • If successful, get roles for the user from an external source.
  • Apply user roles to be used in the code.
  • Mapping user roles to roles in a custom role package

How to do it in ASP.NET Core?

+4
source share
1 answer

cookie Identity, , User.IsInRole(...), [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)
        }
    );
}
0

All Articles