ganders ganders - 5 months ago 99
ASP.NET (C#) Question

Override User.IsInRole in ASP.NET Core

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

, it returns false everytime. If I just call my RoleRepository it works just fine.

Do I need to override the
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:

public async Task<IActionResult> Edit(SchoolEditViewModel model)
model.SchoolInfo = await _schoolRepo.GetSchoolInfo(model.SchoolId, _currentSeason);

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

await SaveSchool(model);

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


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>