4

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?

mason
  • 31,774
  • 10
  • 77
  • 121
Daath
  • 1,899
  • 7
  • 26
  • 42
  • Role and Membership providers are not used in ASP.NET Core (or mvc6) by default (not sure if they can be used at all in core). Identity Framework is the MS provided framework now. This is about IF2, but most should apply http://johnatten.com/2014/06/22/asp-net-identity-2-0-customizing-users-and-roles/ see also http://stackoverflow.com/questions/19541101/add-role-in-asp-net-identity – Erik Funkenbusch Mar 14 '16 at 20:35

1 Answers1

0

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)
        }
    );
}
Xavier Poinas
  • 19,377
  • 14
  • 63
  • 95