這是我創建的一個屬性,可用於指導未經授權的安全操作。它還允許您指定一個將被傳遞給安全控制器上的未授權操作的原因,然後您可以將該原因用於視圖。
您可以創建任意數量的屬性來自定義該屬性以適合您的特定應用程序,只需確保將其添加到RouteValueDictionary。
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public sealed class ApplySecurityAttribute : ActionFilterAttribute
{
private readonly Permission _permission;
public ApplySecurityAttribute(Permission permission)
: this(permission, string.Empty) {}
public ApplySecurityAttribute(Permission permission, string reason)
{
_permission = permission
Reason = reason;
}
public string Reason { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!PermissionsManager.HasPermission(_permission)) // Put security check here
{
var routeValueDictionary = new RouteValueDictionary
{
{ "controller", "Security" }, // Security Controller
{ "action", "Unauthorized" }, // Unauthorized Action
{ "reason", Reason } // Put the reason here
};
filterContext.Result = new RedirectToRouteResult(routeValueDictionary);
}
base.OnActionExecuting(filterContext);
}
}
這裏是安全控制器
public class SecurityController : Controller
{
public ViewResult Unauthorized(string reason)
{
var vm = new UnauthorizedViewModel { Reason = reason };
return View(vm);
}
}
這裏是你想確保
[ApplySecurity(Permission.CanNuke, Reason = "You are not authorized to nuke!")]
這裏,控制器上的屬性聲明PermissionsManager怎麼做的檢查,以查看用戶有權限
public static class PermissionsManager
{
public static bool HasPermission(EZTracPermission permission)
{
return HttpContext.Current.GetCurrentUser().Can(permission);
}
}
http://stackoverflow.com/questions/1315524/is-it-possible-to-override-the-default-behavior-of-authorize-in-asp-net-mvc – womp 2010-01-28 19:46:33