我目前正在开展一个简单的小项目。我有一个存储在数据库中的用户列表,如下所示:
Id, FirstName, LastName, PhoneNo, DomainAC
我在ASP.NET网页上显示了这些信息,并且不确定我现在的进展情况。我现在想:
Domain Account
字段
当前用户Windows域登录。确保这是安全的。
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcApplication1.Models.Employees>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Index
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Index</h2>
<table>
<tr>
<th></th>
<th>
Id
</th>
<th>
FirstName
</th>
<th>
Last Name
</th>
<th>
Phone No.
</th>
<th>
Domain A/C
</th>
</tr>
<% foreach (var item in Model) { %>
<tr>
<td>
<%= Html.ActionLink("Edit", "Edit", new { id=item.Id }) %> |
<%= Html.ActionLink("Details", "Details", new { id=item.Id })%>
</td>
<td>
<%= Html.Encode(item.Id) %>
</td>
<td>
<%= Html.Encode(item.FirstName) %>
</td>
<td>
<%= Html.Encode(item.LastName) %>
</td>
<td>
<%= Html.Encode(item.PhoneNo) %>
</td>
<td>
<%= Html.Encode(item.DomainAC) %>
</td>
</tr>
<% } %>
</table>
<p>
<%= Html.ActionLink("Create New", "Create") %>
</p>
</asp:Content>
我现在如何才能使上面的“编辑”功能仅在域a / c与当前登录匹配时有效,除非您以“Admin”用户身份登录,然后您可以编辑所有内容。 / p>
非常感谢。
答案 0 :(得分:1)
西蒙,
您使用asp.net-mvc标记问题,因此我将基于此给出一个快速示例。
在您的控制器中,您可以装饰整个控制器,也可以只装饰Authorize属性的操作。这意味着您可以明确允许只有特定Roles内的用户才能访问该功能。
通过一个简单的例子:
[Authorize(Roles = "AdminRole, CreditAdvisorRole")]
public ActionResult Edit()
{
var viewModel = _shopService.ShopIndex();
return View(viewModel);
}
因此,该示例仅允许在“AdminRole”和“CreditAdvisorRole”角色中定义的用户访问该功能。这当然是内置行为,在某些时候,你会遇到这种方法的局限性。此时,您可以继续在AuthorizeAttribute上创建自己的覆盖。
此外,由于您没有使用表单身份验证,您将不得不探索更广泛的选项,但覆盖可能能够指导您在该路径上(通过活动目录重新获取信息并应用类似的基于角色的逻辑)
在SO上有一些很好的例子。这一点特别引人注目(参见JohnnyO的回答):
Non-string role names in ASP.NET MVC?
享受..