1

是否可以在 MVC 3 中的特定字段上设置授权?

我最初的想法(和 MSDN 研究)表明 [Authorize] 标签仅用于控制器级别的操作(创建、编辑、索引等)。我可以在控制器操作上执行此操作:

[Authorize(Roles = "RoleA,RoleB")]
   public ActionResult Create()
    {            
        return View(new Tracking());
    } 

场景是两个角色(RoleA 和 RoleB)可以访问“编辑”控制器。但只有 RoleA 可以更改第一个字段。其他角色 (B) 只能查看该字段。

我想在特定领域做这样的事情:

[Required]
[Range(1, 99)]
[Authorize(Roles = "RoleA")]
public int Sequence { get; set; }

更新1:

对 StackOverflow 兔子角色的更多研究表明我需要使用部分视图。

所以在我看来,我添加了这段代码:

<div>
    @if (Context.User.IsInRole("RoleA"))
    {
        @Html.Partial("_SequenceEdit")
    }
    else
    {
       @Html.Partial("_SequenceView")
    }

</div>

因此,如果用户是 RoleA,他们将获得允许编辑“序列”字段的部分视图。否则,他们只能看到“序列”字段。

我的视图只有部分视图如下所示:

<div class="editor-label">
        @Html.LabelFor(model => model.Sequence)
    </div>
    <div class="editor-field">
        @Html.DisplayFor(model => model.Sequence)
        @Html.HiddenFor(model => model.Sequence)
        @Html.ValidationMessageFor(model => model.Sequence)
    </div>
4

1 回答 1

1

我看到您已经想出了如何修改视图以便不向角色 B 中的用户显示文本框。但是您还应该进行服务器端验证以确保只有角色 A 中的用户可以编辑该字段。

[Authorize(Roles = "RoleA,RoleB")]
[HttpPost]
public ActionResult Edit(int trackingID, Tracking newTrackingObject)
{
    // grab the current version of the tracking object from your data repo
    var oldTrackingObject = trackingRepo.GetByID(trackingID);

    // check if the user is in role A and edit the sequence number
    if(Context.User.IsInRole("RoleA"))
        oldTrackingObject.Sequence = newTrackingObject.Sequence;

    // continue processing the new tracking object

    // after all processing is done, persist the edited tracking object back to the repo
    trackingRepo.Update(oldTrackingObject);
    trackingRepo.SaveChanges();
}

这将防止角色 B 中的用户通过手动编辑隐藏的表单字段(例如使用 FireBug 或类似工具)来更改序列字段。

于 2012-04-27T16:00:48.680 回答