[英]ASP.NET MVC: Custom Authorization and MvcSiteMapProvider
在ASP.NET MVC中,我想以某种方式使用MvcSiteMapProvider进行自定义授权。
我知道我可以实现从AuthorizeAttribute继承的自定义Authorization Attribute。 然后,我们也许可以使用[SiteMapAuthorize]装饰控制器。
这是最好的路线吗? 如果是这样,我正在寻找的是正确使用带有授权的站点地图提供程序的实现。
public class SiteMapAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
}
}
谢谢你的帮助!
我有这个工作
这是我的解决方案:
public class SiteMapAuthorizeAttribute : AuthorizeAttribute
{
public string Action { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!httpContext.User.Identity.IsAuthenticated)
return false;
var node = SiteMap.CurrentNode;
// If the node is null, then it was not loaded into memory
// because this user was not authorized to view this node
if (node == null)
return false;
// Check the node's accessibility regardless in case we got passed the above check
return node.IsAccessibleToUser(HttpContext.Current);
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
// If user is not authenticated allow default handling
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
base.HandleUnauthorizedRequest(filterContext);
return;
}
string customErrorPage = GetCustomError("403");
if (customErrorPage == null)
{
base.HandleUnauthorizedRequest(filterContext);
return;
}
// Redirect to 403 (Access Denied) page
filterContext.Result = new RedirectResult(customErrorPage);
}
private string GetCustomError(string statusCode)
{
CustomErrorsSection customErrorsSection = ConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection;
if (customErrorsSection != null)
{
CustomError customErrorPage = customErrorsSection.Errors[statusCode];
if (customErrorPage != null)
return customErrorPage.Redirect;
}
return null;
}
}
HandleUnauthorizedRequest与web.config中的customErrors部分一起使用:
<customErrors mode="On" defaultRedirect="~/Error">
<error statusCode="404" redirect="~/Error/NotFound"/>
<error statusCode="403" redirect="~/Error/AccessDenied"/>
</customErrors>
您需要一个错误控制器来使上述customErrors起作用: 如何在ASP.NET MVC 2中使用CustomErrors
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.