컨트롤러에 대해 [승인]을 활성화 할 수 있지만 단일 작업을 비활성화 할 수 있습니까?

StackOverflow https://stackoverflow.com/questions/329500

  •  11-07-2019
  •  | 
  •  

문제

사용하고 싶습니다 [Authorize] 내 관리자 컨트롤러의 모든 조치에 대해 Login 동작.

[Authorize (Roles = "Administrator")]
public class AdminController : Controller
{
    // what can I place here to disable authorize?
    public ActionResult Login()
    {
        return View();
    }
}
도움이 되었습니까?

해결책

표준 인증 속성 으로이 작업을 수행 할 수는 없지만 AutherizeAttribute에서 자신의 속성을 도출하여 해당 조치에 대한 액세스를 허용하고 액세스 할 수있는 조치 목록을 취할 수 있습니다. 승인의 소스를 볼 수 있습니다. www.codeplex.com 이 작업을 수행하는 방법에 대한 아이디어. 당신이 그렇게했다면, 그것은 다음과 같습니다.

[AdminAuthorize (Roles = "Administrator", Exempt = "Login, Logout") ]
public class AdminController : Controller
{
    public ActionResult Login()
    {
        return View();
    }

    public ActionResult Login()
    {
        return View();
    }

    ... other, restricted actions ...
}

편집하다: Fyi, 나는 결국 나 자신과 비슷한 일을해야 할 필요성을 가로 질러 달렸고 다른 방향으로 갔다. 기본 승인 필터 제공 업체를 만들고 글로벌 인증 필터를 적용합니다. 권한 부여 필터 제공 업체는 반사를 사용하여 작업 또는 컨트롤러에 특정 인증 속성이 적용되는지 확인하고이를 수행합니다. 그렇지 않으면 기본 인증 필터를 적용합니다. 이것은 대중의 액세스를 허용하는 승인에서 파생 된 홍보와 함께 제공됩니다. 이제 기본적으로 안전한 액세스를 얻지 만 공개 액세스 권한을 부여 할 수 있습니다. [Public] 작업 또는 컨트롤러에 적용됩니다. 보다 구체적인 승인도 필요에 따라 적용될 수 있습니다. 내 블로그를 참조하십시오 http://farm-fresh-code.blogspot.com/2011/04/default-authorization-filter-provider.html

다른 팁

승인]으로 컨트롤러를 장식 한 다음 [AllowAnonymous]로 면제하려는 방법을 장식 할 수 있습니다.

컨트롤러의 승인 방법을 무시할 수 있습니다

    protected override void OnAuthorization(AuthorizationContext filterContext)
    {
        if ((string)(filterContext.RouteData.Values["action"]) == "Login")
        {
            filterContext.Cancel = true;
            filterContext.Result = Login();
        }
    }

이것은 작동하지만 해킹입니다.

테스트에 사용되는 전체 클래스 코드 :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace MvcApplication2.Controllers
{
[HandleError]
[Authorize]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewData["Title"] = "Home Page";
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        return View();
    }


    public ActionResult About()
    {
        ViewData["Title"] = "About Page";

        return View();
    }


    protected override void OnAuthorization(AuthorizationContext filterContext)
    {
        if ((string)(filterContext.RouteData.Values["action"]) == "Index")
        {
            filterContext.Cancel = true;
            filterContext.Result = Index();
        }
    }
}
}

실제가 아닐 수도 있지만 내 커스텀 속성을 썼습니다.

public class SelectableAuthorizeAttribute : AuthorizeAttribute
{
    public SelectableAuthorizeAttribute(params Type[] typesToExclude)
    {
        _typesToExlude = typesToExclude;
    }

    private readonly Type[] _typesToExlude;

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        bool skipAuthorization = _typesToExlude.Any(type => filterContext.ActionDescriptor.ControllerDescriptor.ControllerType == type);

        if (!skipAuthorization)
        {
            base.OnAuthorization(filterContext);
        }
    }
}

그런 다음 글로벌 필레 트에 등록했습니다.

filters.Add(new SelectableAuthorizeAttribute(typeof(MyController)));

누군가에게 유용하기를 바랍니다

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top