0

I am trying to hide a link or would not be able to go to the page if the user is not an administrator. I am able to do the latter using this code in my controller:

[AuthorizeRoles("Admin")]
public ActionResult Registration()
{
   return View();
}

When I try to hide the link using this code:

@if (!Context.User.Identity.Name.IsEmpty())
{
    <li id="dd_vehicle" class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown">VEHICLE <b class="caret"></b></a>
    <ul class="dropdown-menu">
    @if (ViewContext.HttpContext.User.IsInRole("Admin"))
    {
        <li id="item_registration">
            @Html.ActionLink("Registration", "Registration", "Home")
        </li>
    }
}

The link gets hidden. But when I login as "Admin", still the link doesn't show.

This is how I AuthorizeAttribute:

public class AuthorizeRolesAttribute : AuthorizeAttribute
{
    private readonly string[] userAssignedRoles;

    public AuthorizeRolesAttribute(params string[] roles)
    {
        this.userAssignedRoles = roles;
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        bool authorize = false;
        using (var db = new SMBI_DBEntities())
        {
            var um = new UserManager();
            foreach (var roles in userAssignedRoles)
            {
                authorize = um.IsUserInRole(httpContext.User.Identity.Name, roles);
                if (authorize)
                    return authorize;
            }
        }
            return authorize;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new RedirectResult("~/Home/UnAuthorized");
    }
}

and this is in LoginView:

[HttpPost]
public ActionResult Login(UserLoginView ulv, string returnUrl)
{
    if (ModelState.IsValid)
    {
        var um = new UserManager();
        var password = um.GetUserPassword(ulv.LoginName);

        if (string.IsNullOrEmpty(password))
        {
            ModelState.AddModelError("", "Login ID and Pasword do not match.");
        }
        else
        {
            if (ulv.Password.Equals(password))
            {
                FormsAuthentication.SetAuthCookie(ulv.LoginName, false);
                return RedirectToAction("Registration", "Home");
            }
            else
            {
                ModelState.AddModelError("","Password provided is incorrect.");
            }
        }
    }
    return View(ulv);
}

Hope you could help. Thank you.

Ibanez1408
  • 4,550
  • 10
  • 59
  • 110
  • The AuthorizeAttribute doesn't work for the view side; it becomes a little more complicated in that regard... there are some good resources online that can help in that regard. – Brian Mains Jul 25 '17 at 01:57

1 Answers1

0

Hi You may try like the below:

@if(Page.User.IsInRole("Admin"))
 {
        <li id="item_registration">
            @Html.ActionLink("Registration", "Registration", "Home")
        </li>
}

Helpful link:How to use Page.User.IsInRole

And just as an additional info, you can also write helper like below for the future purpose if required

public static class PrincipalExtensions
{
    public static bool IsInAllRoles(this IPrincipal principal, params string[] roles)
    {
        return roles.All(r => principal.IsInRole(r));
    }

    public static bool IsInAnyRoles(this IPrincipal principal, params string[] roles)
    {
        return roles.Any(r => principal.IsInRole(r));
    }
}

Now simply you could call this extension method like this:

// user must be assign to all of the roles  
if(User.IsInAllRoles("Admin","Manager","YetOtherRole"))
{
    // do something
} 

// one of the roles sufficient
if(User.IsInAnyRoles("Admin","Manager","YetOtherRole"))
{
    // do something
} 

Source: https://stackoverflow.com/a/32385065/3397630

Thanks

Karthik Elumalai
  • 1,574
  • 1
  • 11
  • 12
  • Karthik, where should I put the "PrincipalExtensions"? Should it be in another class? How do I implement it? – Ibanez1408 Jul 25 '17 at 02:32
  • I get this error: Cannot perform runtime binding on a null reference pointing to "@if (Page.User.IsInRole("Admin"))" – Ibanez1408 Jul 25 '17 at 02:41
  • yup "PrincipalExtensions" is a separate class, Once you written you will get the additional methods like IsInAllRoles,IsInAnyRoles to the user object. And for the error "Cannot perform runtime binding on a null reference " there could be other reason ,kindly check this url https://forums.asp.net/t/1885663.aspx?Cannot+perform+runtime+binding+on+a+null+reference+ – Karthik Elumalai Jul 26 '17 at 02:23