모든 컨트롤러 동작에 대한 작업 필터 시행 (C# / ASP.NET MVC)
-
20-09-2019 - |
문제
세션 값을 기반으로 컨트롤러 작업에 대한 액세스를 승인하는 새로운 액션 필터 ([Authorize]와 유사한 속성)를 만들었습니다. 그러나 나는 기본적으로 그 속성으로 모든 컨트롤러 동작을 장식하고 있습니다 (거의 제외).
그래서 나는 그 액션 필터를 갖는 것이 더 좋을 것이라고 생각했습니다. 언제나 실행 제외하고 컨트롤러 동작에 [ExemptromaHuthorize] 속성을 첨부하는 경우? (아마도 내 컨트롤러 클래스를 물려받을 수 있습니까?)
어떻게 할 수 있습니까?
해결책
달리기 jeef3대답, 나는 이것을 생각해 냈다. 다중 구분 된 동작과 같이 더 많은 오류 확인 및 견고성을 사용할 수 있지만 일반적인 아이디어는 효과가 있습니다.
특정 경우 세션 값을 테스트하고 승인에서도 반환하기로 결정할 수도 있습니다.
public class AuthorizeWithExemptionsAttribute : AuthorizeAttribute
{
public string Exemption { get; set; }
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.RouteData.GetRequiredString("action") == Exemption)
return;
base.OnAuthorization(filterContext);
}
}
용법:
[AuthorizeWithExemptions(Roles="admin", ExemptAction="Index")]
public class AdminController : Controller
...
다른 팁
CodeProject에서 내 기사를 확인하십시오.
http://www.codeproject.com/kb/web-security/authorizewithexemptions.aspx
이 기사에서는 ASP.NET MVC 애플리케이션의 컨트롤러를 안전하게 정의하는 것을 제외하고 모든 조치를 보호하는 방식으로 ASP.NET MVC 애플리케이션 컨트롤러를 보호하기위한 솔루션을 제공하겠습니다.
코드의 스나이퍼 :
public override void OnAuthorization(AuthorizationContext filterContext)
{
ActionDescriptor action = filterContext.ActionDescriptor;
bool IsUnsecured = action.GetCustomAttributes(
typeof(UnsecuredActionAttribute), true).Count() > 0;
//If doesn't have UnsecuredActionAttribute - then do the authorization
filterContext.HttpContext.SkipAuthorization = IsUnsecured;
base.OnAuthorization(filterContext);
}
나는 질문이 꽤 오래되었지만 어쨌든 이해한다.
protected void Application_Start()
{
// your code here and then
RegisterGlobalFilters(GlobalFilters.Filters);
}
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new MyActionFilterAttribute());
}
ACTION 필터에서 작업이 다음과 같은 방식으로 다른 속성이 있는지 확인할 수 있습니다.
public void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.ActionDescriptor.IsDefined(typeof(AnotherActionAttribute), false))
{
// do what you want to do
}
}
시도하고 추가 할 수도 있습니다 Except
첫 번째 속성에 대한 속성?
[MyAuthenticate(Exempt="View")]
public class MyController : Controller
{
public ActionResult Edit()
{
// Protected
}
public ActionResult View()
{
// Accessible by all
}
}
클래스에 속성을 추가하여 해당 클래스의 모든 메소드에 적용 할 수 있습니다.
[Authenticate]
public class AccountController : Controller
{
public ActionResult Index()
{
return View();
}
}
클래스 수준 속성에서 특정 메소드를 제외하는 방법을 모르겠습니다. 무단 요청에 별도의 컨트롤러를 사용합니까?
2013 년 이상이 글을 읽는 사람이라면 MVC4는 이제 [allowanonymous]의 사용을 지원합니다.
컨트롤러에 권한을 부여한 다음 승인하지 않으려는 기능에 익명을 허용 할 수 있습니다.
예시:
승인] 공개 클래스 홈 컨트롤러 : 컨트롤러 {
[AllowAnonymous] public ActionResult Index() { }
}
이것은 사용자 정의 [myauthorize] 필터와 함께 작동합니까? 아니면 [인증]에서만 작동합니까?
2013 년 이상이 글을 읽는 사람이라면 MVC4는 이제 사용을 지원합니다. [AllowAnonymous]
컨트롤러에 권한을 부여한 다음 승인하지 않으려는 기능에 익명을 허용 할 수 있습니다.
예시:
[Authorize]
public class HomeController : Controller
{
[AllowAnonymous]
public ActionResult Index()
{
}
}