我的朋友,你和我在同一条船上!我设法通过自定义授权属性做到了这一点。以下是我在这个过程中偶然发现的几点。
我没有创建自己的用户表。您可以,但您可以根据域中的用户数量查询 AD 用户,并使用 Guid 将其链接到您的角色/活动表进行搜索。如果您确实创建了一个反映 AD 的用户表,请使用该用户的 Guid。这样,如果登录名/名称/其他任何内容发生变化,Guid 将保持不变。
自定义授权属性:
namespace YourSite.Attributes
{
[AttributeUsage(AttributeTargets.Method)]
public class AuthRoleAttribute : ActionFilterAttribute
{
public string RoleName { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!ViewIsAuthorizedActivity(RoleName)) // create a bool function to see if your user is in this role... check your db or whatever
{
string requestMethod = filterContext.HttpContext.Request.HttpMethod;
if (requestMethod == "GET")// I chose two different means of forbidding a user... this just hides the part of the page based on the @if(ViewBag.Authorization = "FORBIDDEN") where you render a partial, else show the view
{
filterContext.Controller.ViewBag.Authorization = "FORBIDDEN";
}
else if (requestMethod == "POST") // This prevents over posting by redirecting them completely away from that controller... also prevents them from posting if they have the page loaded and you remove permission
{ // Hiding a part of the page doesn't matter for the POST if the page is already loaded
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "controller", "Home" },
{ "action", "Forbidden" },
{ "area", ""}
});
}
base.OnActionExecuting(filterContext);
}
}
}
}
视图中如何处理 GET:
@if (ViewBag.Authorization == "FORBIDDEN")
{
ViewBag.Title = "Forbidden!";
@Html.Partial("~/Views/Forbidden.cshtml");
}
else
<!-- User is not forbidden and have the view here -->
请注意,对于 POST,用户会从控制器重定向到 Forbidden 控制器。
控制器上的属性:
[AuthRole(RoleName = "Admin")]
public ActionResult YourController()
我还对用户进行了扩展,因此如果他们没有权限,某些内容可能会隐藏在视图中:
public static bool IsAuthorized(this IPrincipal user, string roleName)
{
return Attributes.AuthActivityAttribute.ViewIsAuthorizedByRole(roleName); // function determining if the user is in that role, therefore show what you want to show in the view or don't show it if false
}
调用者:
@if (User.IsAuthorized("Admin"))
{
<!-- show something, a link, etc. -->
}
希望这能让您比我有一个更好的开端。如果您有任何问题,请告诉我。