ASP.NET MVC: пользовательская авторизация и MvcSiteMapProvider - PullRequest
0 голосов
/ 22 июня 2011

В ASP.NET MVC я бы хотел как-то выполнить пользовательскую авторизацию с помощью MvcSiteMapProvider.

Я знаю, что могу реализовать пользовательский атрибут авторизации, который наследуется от AuthorizeAttribute.Затем, возможно, мы можем декорировать контроллеры, например, с помощью [SiteMapAuthorize].

Это лучший маршрут?Если это так, то я ищу правильную реализацию использования поставщика карты сайта с авторизацией.

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

    }
}

Спасибо за любую помощь!

1 Ответ

0 голосов
/ 28 октября 2011

У меня это работает

Вот мое решение:

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 работает с разделом customErrors в web.config:

<customErrors mode="On" defaultRedirect="~/Error">
  <error statusCode="404" redirect="~/Error/NotFound"/>
  <error statusCode="403" redirect="~/Error/AccessDenied"/>
</customErrors>

Вам понадобится контроллер ошибок для работы указанных выше пользовательских ошибок: Как использовать CustomErrors в ASP.NET MVC 2

...