2
votes

Within MVC 3, I am trying to figure out how to apply both role and user based security properly (and following best practices) to one of my views. I have a view that lists details for any given "member" (aka user). I want all members to be able to view the details for any other member, but if the member is viewing their own detail, I want them to be able to edit their own details. Also, a site administrator should be able to edit any members detail.

For your reference, my site is configured as follows:

  • I created my own authentication provider (not using or overriding the SqlMembershipProvider) that is very simple and uses forms authentication.
  • I overrode the default RoleProvider to implement my own methods for IsUserInRole and GetRolesForUser. Both methods are working fine.
  • All of my views use "flattened" view models that map from my concrete entities.
  • My Detail view is used for both displaying information and editing information. A flag (called IsInEditMode) is used (and passed into a custom HtmlHelper) to determine whether or not to simply display the data or provide an editor field. I would like to keep this single view.

Here are my specific requirements. I am listing them all in this question, as I believe that the correct answer will/should address all these concerns (let me know if this is incorrect):

  1. Members should be able to view any other member's detail.
  2. Members should be able to edit most of their own detail, but some aspects of their detail should only be editable by a site administrator (e.g. Status of approved or provisional)
  3. Members that belong to the "Site Administrator" role can edit everything.
  4. The "Edit" button within the detail view needs to be displyed only based on the member's role (as Site Administrator) or verification of the users id/name with their login credentials.
  5. The controller HttpPost Edit action needs to verify that the user is approved to edit. I know I can decorate the action with a role like [Authorize(Roles = "Site Administrator")], but I don't know how to implement an OR UserBeingEdited == LoggedInUser attribute.
  6. In addition, I want to prevent malicious edits such as a user "fiddling" with the user ID value returned as well as XSS and CSRF attacks.

Below is my applicable code (that doesn't have any security applied) for the controller and view. Any suggestions are appreciated!

MemberController.cs Edit Action sippet:

[HttpPost]
[ValidateAntiForgeryToken]
//TODO: Find out how to allow only "Site Administrator" roles OR the logged in user to edit their own information
public ActionResult Edit(MemberDetailViewModel memberDetailViewModel)
{
  if(ModelState.IsValid)
  {
    //TODO: Find out how to prevent member ID tampering (including XSS and CSRF attacks)
    var updatedMember = _memberServices.Find(memberDetailViewModel.MemberId);
    Mapper.Map(memberDetailViewModel, updatedMember);
    _memberRepository.InsertOrUpdate(updatedMember);
    return RedirectToAction("Detail", new {id = memberDetailViewModel.MemberId});
  }
  else
  {
    return View("Detail", _memberQueries.GetMemberDetailViewModel(memberDetailViewModel.MemberId, isInEditMode:true));
  }
}

Member Detail.cshtml View (only relevant parts included):

@model MyApp.Web.Areas.Members.Models.MemberDetailViewModel
@using (Html.BeginForm("Edit", "Member", FormMethod.Post, new { id = "memberDetailForm", enctype = "multipart/form-data" }))
{
  <fieldset id="pageTitle">
    <h2>
      <!-- TODO: Only allow editing by "Site Administrators" or the verified logged in user -->
      @if (Model.IsInEditMode)
      {
        @:Editing @Model.FirstName @Model.LastName
        <a class="button" href="@Url.Action("Detail", new { id = @Model.MemberId })">Cancel</a>
        <input class="button" type="submit" value="Save" />
        @Html.HiddenFor(x => Model.MemberId)
        @Html.AntiForgeryToken()
      }
      else
      {
        @:Details for @Model.FirstName @Model.LastName
        <a class="button" href="@Url.Action("Edit", new { id = @Model.MemberId })">Edit</a>
      }
    </h2>
  </fieldset>
  <fieldset>
      <legend>Basic Information</legend>
      <table>
        <tr>
          <td class="label">
            First Name:
          </td>
          <td class="field">
            @Html.DisplayOrEditorFor(x => Model.FirstName, Model.IsInEditMode)
            @Html.ValidationMessageFor(x => Model.FirstName)
          </td>
        </tr>
        <!-- Other properties omitted -->
        <tr>
          <td class="label">
            Status: 
          </td>
          <td class="field">
            <!-- TODO: This status field should only be editable by "Site Administrator", not the user -->
            @Html.DisplayOrEditorDropDownListFor(x => Model.StatusId, Model.StatusList, Model.IsInEditMode)
          </td>
        </tr>
      </table>
  </fieldset>
}

If needed to better understand my view, here is a sample of my DisplayOrEditorFor custom HtmlHelper function:

public static MvcHtmlString DisplayOrEditorFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, bool isInEditMode)
{
  return isInEditMode ? System.Web.Mvc.Html.EditorExtensions.EditorFor(htmlHelper, expression) : System.Web.Mvc.Html.DisplayExtensions.DisplayFor(htmlHelper, expression);
}
1

1 Answers

3
votes

The easiest solution in your case is to only set IsInEditMode when the id of the edited user == the id of the current user, or the user is an administrator.

You don't want to use anything other than a generic Authorize attribute, because all registered users can access the page, thus you don't want or need additional auth on the page itself, just on the fields, and those fields are controlled by your IsInEditMode boolean.

You would also do a test on the "Edit" link to see if it's the current user or admin, as well as special tests for fields where only the admin can edit.

So, you would do something like this:

@Html.DisplayOrEditorDropDownListFor(x => Model.StatusId, Model.StatusList, 
     Model.IsInEditMode && User.IsInRole("Administrator"))

Whether it's in Edit mode will be set in the controller. It will only allow EditMode to be set true if it's the current user or an admin.