2011-06-22 128 views
0

在ASP.NET MVC中,我想以某種方式使用MvcSiteMapProvider進行自定義授權。ASP.NET MVC:自定義授權和MvcSiteMapProvider

我知道我可以實現繼承自AuthorizeAttribute的自定義授權屬性。然後,我們也許可以用[SiteMapAuthorize]來裝飾控制器。

這是最好的路線?如果是這樣,我正在尋找的是使用帶授權的站點地圖提供程序的正確實施。

public class SiteMapAuthorizeAttribute : AuthorizeAttribute 
{ 
    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 

    } 
} 

感謝您的幫助!

回答

0

我有這方面的工作

這裏是我的解決方案:

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> 

您將需要一個Errors Controller for the custom customErrors work: How to use CustomErrors in ASP.NET MVC 2