2

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});
    }
ganders
  • 6,935
  • 13
  • 61
  • 109
  • 1
    Doesn't the `IPrincipal` stuff still have it? You could just write an extension method to achieve the same thing. Does the attribute still exist in core? – Callum Linington Jul 14 '16 at 14:26
  • Here is an example from aspnet source code on github: https://github.com/aspnet/Mvc/blob/dev/test/WebSites/FiltersWebSite/Filters/AuthorizeUserAttribute.cs – Callum Linington Jul 14 '16 at 14:28
  • Looks like you have us `IAuthorizationFilter` stuff now. – Callum Linington Jul 14 '16 at 14:29
  • FYI, it's now called ASP.NET Core. There was just a new release late last month. If you're not on ASP.Core 1.0 RTM (requires Visual Studio Update 3) and Visual Studio tooling preview 2, I would suggest updating to the latest versions. This should work. I use it in a number of razor pages. – Clint B Jul 14 '16 at 14:59
  • @ClintB did it NOT work prior to Update 3? – ganders Aug 16 '16 at 18:15

1 Answers1

0

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>
}
Community
  • 1
  • 1
ganders
  • 6,935
  • 13
  • 61
  • 109