1

I've been looking around how to use roles in SPA, and the basic project that Visual Studio (2019) creates is quite fine, however [Authorize(Roles="")] does not work properly, so I can use Authorize attribute to check if user is actually logged in but not the role.

My approach now in controllers is to get the user and use IsInRole(), but this seems like a big overhead since I should have his token already which should include the role.

ClaimsPrincipal currentUser = this.User;
var currentUserId = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
User user = await _userManager.FindByIdAsync(currentUserId);

if (await _userManager.IsInRoleAsync(user, "Admin"))
...
  • 1
    UPDATE: So it turns out the proper authentication scheme for me was `Identity.Application`. Using it this way `[Authorize(Roles="...", AuthenticationSchemes ="Identity.Application")]` works. – Zsolt Kálmán Dec 17 '19 at 09:10

1 Answers1

0

You should stick to the original [Authorize(Roles="")] attribute.

As stated here:Store/assign roles of authenticated users

Roles are added to the IPrincipal of the HttpContext. You can create a GenericPrincipal, parse the list of roles in the constructor and set it as HttpContext.User. The GenericPrincipal will then be accessible through User.IsInRole("role") or the [Authorize(Roles="role")] attribute

Depending on your authentication scheme, you need to create a GenericPrincipal and add the roles there for all requests so that they can be accessed.

Example for FormsAuthentication is in the mentioned answer.

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61