2010-03-30 2 views
1

자신의 보안을 수행하는 ASP.NET MVC 사이트를 유지 관리하고 있습니다. 그래서 그들은 AuthorizeAttribute에서 파생 된 클래스를 만들었습니다. OnAuthorization에는 RouteDataaction 이름을 기반으로 메서드를 찾는 리플렉션 코드가 있습니다.리플렉션을 사용하여 컨트롤러에서 실행될 메소드 찾기

IList<MethodInfo> methods = filterContext.Controller.GetType().GetMethods().Where(i=>i.Name == action).ToList(); 

foreach (MethodInfo method in methods) 
{ 
    //get all of the controller security properties, and check for access: 
    object[] props = method.GetCustomAttributes(typeof(ControllerSecurity), false); 
    foreach (ControllerSecurity prop in props) 
    { 
     //does the user have access to this area/action? 
     authorized = security.ValidateUserForAction(prop.SecurityArea, prop.SecurityAction); 

     //if we are authorized by one ControllerSecurity, then we are good. 
     if (authorized) 
     { 
      break; 
     } 
    } 
} 

ControllerSecurity 클래스는 다음과 같습니다

내가 볼 문제 만 AcceptVerb, 또는 매개 변수에 의해 다른 컨트롤러에서 여러 액션 기능이있는 경우, 그것은 사용자 수 허용하지 것입니다 이 기능에 필요한 보안 액세스를 우리의 컨트롤러 액션을 장식하고 설명하는 데 사용되는 속성 클래스 :

//User needs to have VIEW privileges to REPORTS area: 
[ControllerSecurity("REPORTS", "VIEW")] 
public ActionResult Index(){...} 

는 보안을 다시 작성하지 않고,이 일을 더 나은 방법이 있어야합니다. 나는 우리가 결국 실행될 방법만을 점검한다는 것을 확실하게 알고 싶다.

나는 AuthorizationContext 개체를 살펴 봤으며 결국에는 결국 호출 될 작업 메서드를 확실히 찾을 수 없습니다.

누구든지 아이디어가 있습니까?

+0

특성은 동작 자체에 있으므로 실제로 작동하는 특성을 찾을 때까지 모든 동작 특성을 반복 할 수 있습니까? –

+0

하지만 내 컨트롤러에 두 개의'Index' 액션이 있다면, 각기 다른 매개 변수를 가지고 각각 다른 보안 속성을 가질 수 있습니다. (아마도 실제로는 일어나지 않을 것입니다.하지만 보안 코드가 가능한 한 꽉 찬 것을 좋아합니다.) – mlsteeves

+0

자세한 내용은 여기를 참조하십시오. http://stackoverflow.com/questions/2168942/c-custom-attributes-how-to-get-the -member-type-to-the-attribute-was-appl –

답변

0

Mvc는 특정 동작에 이미 액세스 할 수있는 방법을 제공한다고 생각합니다. 나는 그것을 시도했지만이 시도 ..

object[] props = filterContext.ActionDescriptor.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), false); 
foreach (ActionMethodSelectorAttribute prop in props) 
{ 
     //does the user have access to this area/action? 
     authorized = security.ValidateUserForAction(prop.SecurityArea, prop.SecurityAction); 

     //if we are authorized by one ControllerSecurity, then we are good. 
     if (authorized) 
     { 
       break; 
     } 
} 

것은주의하는 filterContext.ActionDescriptor하지 않은, 그것은 OnAuthorization 방법에 전달되는 AuthorizationContext에 존재합니다.

작동하지 않는 경우 코드 찾기 작업에서 ActionNameSelectorAttribute을 사용할 수 있습니다. 표시 한 코드가 항상 작동하지는 않습니다. 묵시적 메소드 이름 대신 액션을 정의하기 위해 명시 적으로 ActionName["MyAction"]을 사용하여 다른 사람의 사례를 취하십시오.

+0

'AuthorizationContext' 객체는'Actiondescriptor' 멤버가 없습니다. (http://msdn.microsoft.com/en-us/library/system.identitymodel.policy.authorizationcontext_members.aspx) – mlsteeves

+0

명시 적으로'ActionName [ "MyAction"]'을 사용하는 사람에 대한 좋은 지적! – mlsteeves

+2

잘못된 클래스 (잘못된 네임 스페이스) ( http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizationcontext_members(VS.100).aspx) – Jab

관련 문제