Renato
Renato

Reputation: 119

Hiding menu according to permission in asp.net core

I need to check if user has permission, if he does not have permission the menu item will not appear.

I'm trying to check through @UserManager.GetUserName(User), but I can not get all the data contained in the Identity table to see if user has permission, in the example below he does not recognize the word "Cidades".

    <ul class="dropdown-menu " role="presentation">
     @if (UserManager.GetUserName(User.Cidades) == true)
     {
        <li><a asp-page="/Cidade/Index">Cidades</a></li>
     }

In a page with controller I do it this way and it works well:

ApplicationUser user = await UserManager.GetUserAsync(User);
            bool cidade = user.Cidades;
            if ( cidade == true)
            {
                return Page();
            }
            else
            {
                return RedirectToPage("/Error");
            }

How would be the right way to do it in the _Layout.cshtml view?

Upvotes: 2

Views: 1936

Answers (1)

Obay Abd-Algader
Obay Abd-Algader

Reputation: 1267

Use View-bsed authorization

Basically it says:

  1. inject authorization service

    @inject IAuthorizationService AuthorizationService

  2. Use the service as follow

    @if ((await AuthorizationService.AuthorizeAsync(User, "PolicyName")).Succeeded) {

    This paragraph is displayed because you fulfilled PolicyName.

    }

An important notice:

Don't rely on toggling visibility of your app's UI elements as the sole authorization check.

Upvotes: 2

Related Questions