Tuesday, March 1, 2011

ASP.NET / MVC.NET tag for checking roles (equivalent of declarative attribute PrincipalPermission)

I use declarative roles in my MVC.NET controllers and I have a custom membership & roles provider.

This works fine:

 [Authorize(Roles = "ADMIN")]

Also, I have a base MVC.NET CustomController class that all controllers derive from, and it has a "currentUser" property that is auto-fetched from the session on demand, so all controller code just refers to "currentUser" and doesn't worry about sessions, httpcontext, etc. I've implemented the membership provider properly, as it works with other parts of the framework that just deals with providers, but until now I had not tried to access the "User" principal from a view.

What is the simplest syntax for check roles in a view page? I know I can use a helper to generate a partial view but I don't want that here, I want to explicitly wrap some sections of a page in some role checks.

Something like this:

<% if(currentUser.IsInRole("ADMIN") { %>
...
<% } %>

Thanks.

From stackoverflow
  • The simplest way is to do exactly what you are doing, checking the current user in the context. You can access the User principal on the current HttpContext through the ViewPage's ViewContext property.

    var currentUser = this.ViewContext.HttpContext.User;
    
    mrjoltcola : I was mistaken (memory getting bad). I did not write a custom Membership/Roles provider, what I wrote was a WCF custom authentication and authorization (custom IPrincipal, UserNamePasswordValidator and IAuthorizationPolicy). So I can use Thread.CurrentPrincipal in my WCF service code, and the declarative "PrincipalPermission" attribute works. I want to reuse that code for my MVC.NET security. I need to edit my question, sorry for the confusion.
    mrjoltcola : On second thought, your answer is useful, assuming my question was accurate. So I will leave it and open a different question regarding reuse of WCF custom principals and ASP.NET/MVC.NET membership provider. So per your answer, what is the syntax to access "this.ViewContext.HttpContext.user" from the view page?
    tvanfosson : @mrjoltcola - the syntax in my example should be correct, `this` refers to the specific ViewPage instance that you are working with.
    mrjoltcola : It seems I can use either of these. <% if(HttpContext.Current.User.IsInRole("ADMIN") ) { %> or <% if(ViewContext.HttpContext.User.IsInRole("ADMIN") ) { %>, the latter being MVC.NET specific I assume. I found in the end, the reason it wasn't working for me was I had not set my custom principal into the HttpContext.Current.User at all, so it was using some GenericPrincipal which was different from my "currentUser" in my controller. After I set it, its good, pluus I've changed the currentUser property to fetch from HttpContext now and all is good. Thanks!

0 comments:

Post a Comment