January 11, 2016
Adding Security To Html Helpers
Posted by Brian Mains under .NET, ASP.NET MVC, Razor | Tags: asp.net, bootstrap, control, mvc, razor, security, twitter |No Comments
I know the new MVC 5 HTML tag attributes for rendering ASP.NET widgets is all the rage, but there are a lot of useful approaches to using the server-side HTML helpers. One simple extension method we are going to look at is adding control level security. Often within our applications, we have a means of providing UI security at the control level. We may, for instance, hide a control if the user doesn’t belong to a certain role. It’s really simple to add this as an extension to IHtmlString, which is what HTML tag helpers do. First, let’s look at how this might be used:
@Html.TextBoxFor(i => i.AccountID).IfInRole("ADMIN")
Notice how our textbox has an IsVisible method; this checks if the user is in the ADMIN role, and if so, it does the following:
public static IHtmlString IfInRole(this IHtmlString html, string role) { if (HttpContext.Current == null) return html; if (HttpContext.Current.User.IsInRole(role); return html; else return new MvcHtmlString(""); }
In this method, if the user doesn’t have permissions, it outputs a blank string instead of the original HTML, thus providing some level of control security. We could use claims to do this, or some other security feature; it really doesn’t matter what is used behind the scenes. Also, we could also provide some default template to use if the control is hidden, as a blank space may not be optimal. This can especially be the case if you are using Twitter Bootstrap, because your form may look like:
<div class="form-group"> <label class="control-label">Account</label> @Html.TextBoxFor(i => i.AccountID, new { @class = "form-control" }) </div>
And thus a wrapper around it like:
@if (Html.IsInRole("Admin")) { <div class="form-group">..</div> }
Or using a lambda template might be better. When there is supporting HTML wrapping the HTML Helper, showing or hiding may be a little more complicated depending on your design. I hope you see from this simple example how you can add some security features into your application using the old-school HTML helpers.