7

I'm trying to figure out how to show/hide links for users based on their roles. I know how to set the authorize attribute for an action method, but I'm having trouble making links show hide in a view if the user is say, an admin or a manager in my roles database.

Any good articles or code example someone can point me towards?

4 Answers 4

11

In your view you can reference the IPrincipal user through the System.Web.Mvc.ViewPage's User property.

E.g. In your view you can have something like:

<% if (User.IsInRole("Admin")) { %>
    <%= Html.ActionLink("Admin only link", "Edit", "Users") %>
<% } %>

<% if (User.IsInRole("Manager") || User.IsInRole("Admin")) { %>
    <%= Html.ActionLink("Manager & Admin only link", "Edit", "Product") %>
<% } %>

HTHs,
Charles

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Here's a twist - I have my tab links in the master page and I want a tab to appear for certain roles. Do you know how I can add a reference to my master for the IPrincipal?
Use either HttpContext.Current.user or ViewContext.HttpContext.User - that should do the trick :-)
Ahh, now I can move on with things... I appreciate the help!
2

This is one thing i really dont like with MVC (as in ASP.Net MVC, not the pattern) there is a tendancey to moving of UI logic into the markup.

There is no way to run Unit tests on that logic once its in the aspx.

Personly i think webforms with a suitable UI pattern (MVC or MVP etc) would better suit than having the page littered with conditional logic that cant be tested.

2 Comments

As I still consider myself a beginner, I am getting better and better and I completely agree with what you are saying and have littered the heck out of my markup pages. I work in webforms at my day job and MVC on my freelance projects and have many conflicting headaches with learning both at the same time. Although I haven't learned much about how to unit test - I will no doubt need it one day in the near future; and I'm hoping by then the MVC team will have addressed this. Thanks for the comment +1 -ben
Use Selenium for UI testing. You can run tests using different roles and then test for the existence of HTML controls (hey that rhymes).
1
<% if(HttpContext.Current.User.IsInRole("Admin")){%> <a href="/Admin">Admin</a> <% } %>

Use this code. This is easier.

Comments

0

I use a static class for Role validation and in the cshtml i used this class, the role validation is out the cshtml.

I have my Authorized functions or content in database (by user or by role) so you dont have to redeploy if the access definition change.

public static class AuthorizeContent
{
    public static bool AuthorizeAccessContent(string Content)
    {
        bool bReturn = false;
        DBContext db = new DBContext();
        string[] RolesUser = Roles.GetRolesForUser(WebSecurity.CurrentUserName);

        foreach (AuthorizedContentRole aut in db.AuthorizedContentRole)
        { 
            foreach (string rol in RolesUser)
            {
                if (aut.Role==rol && aut.Content==Content)
                {
                    bReturn = true;
                    break;
                }
            }
        }
        foreach (AuthorizedContentUser aut in db.AuthorizedContentUser)
        {
            if (aut.UserName == WebSecurity.CurrentUserName && aut.Content == Content)
            {
                bReturn = true;
                break;
            }
        }

        return bReturn; 
    }

/// in the cshtml

@if (AuthorizeContent.AuthorizeAccessContent(Content))
{

    <li class="two">
        <h5>Administrator link</h5>
        @Html.ActionLink("Admin secret info","Index", "Information")
    </li>
}

you could also use a filter like [AccionAuthorize(Action="MyContent")]

public class AccionAuthorizeAttribute : AuthorizeAttribute
{
    public string Action { get; set; }
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            filterContext.Result = new HttpUnauthorizedResult();
        else if (!AutorizacionContenido.AutorizaAccesoContenido(Action))
            filterContext.Result = new HttpUnauthorizedResult();
        base.OnAuthorization(filterContext);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.