ganders ganders - 3 months ago 67
ASP.NET (C#) Question

Override User.IsInRole in ASP.NET Core

I've got an MVC 6 website (asp.net core/5) where I need to check if a user is in specific roles or not from the razor pages. Whenever I call

User.IsInRole("{rolename}")
, it returns false everytime. If I just call my RoleRepository it works just fine.

Do I need to override the
User.IsInRole()
functionality someplace, or is that method obsolete in ASP.NET Core?

Here's my implementation so far:

if (User.IsInRole("Admin") || User.IsInRole("SuperUser") || User.IsInRole("DataIntegrity"))
{
model.IsDataIntegrity = true;
}


This works correctly when I call it via the Authorize policy, like this:

[Authorize("DataIntegrity")]
[ValidateAntiForgeryToken]
[HttpPost]
[Route("team/edit/{schoolId:int:min(1)}/{schoolName?}")]
public async Task<IActionResult> Edit(SchoolEditViewModel model)
{
model.SchoolInfo = await _schoolRepo.GetSchoolInfo(model.SchoolId, _currentSeason);

IsModelValid(model);
if (!ModelState.IsValid)
{
return View(await ApplyUnboundProperties(model));
}

await SaveSchool(model);

return RedirectToAction("Live", "SchoolMain", new {schoolId = model.SchoolId, schoolName = model.SchoolInfo.SchoolName});
}

Answer

More googling and here's what I found works for me:

Checking login user AuthorizePolicy in Razor page on Asp.Net Core

More specifically, I needed to inject the IAuthorizationService into my views (or controllers), and then call the AuthorizeAsync method.

(In View)

@inject IAuthorizationService AuthorizationService

...

@if (await AuthorizationService.AuthorizeAsync(User, "PolicyName"))
{
    <p>This paragraph is displayed because you fulfilled PolicyName.</p>
}