2012-10-09 2 views
0

컨트롤러 수준에서 리소스를로드하고 권한을 부여하는 구현/예를 찾고있었습니다. 나는 cancan에서 load_and_authorize_resource과 같은 기능을 찾고있다. 루비에있는 보석.레일에서 mvc .net으로 load_and_authorize_resource 가져 오기

누구나 하나의 예를 들어 보았습니다 .Mvc .Net 속성을 사용하여 비슷한 것을 구현하는 방법은 무엇입니까?

감사합니다.

는 load_and_authorize_resource 행동 레일, 컨트롤러와 모델 이름으로

이 규칙에 의해 연결되어있다. 속성 load_and_authorize_resource은 이점을 취합니다. 리소스 인스턴스가 필요한 동작이 발생하면 load_and_authorize_resource은 리소스 인스턴스에 액세스 할 수 있는지 여부를 확인합니다. 가능한 경우 인스턴스 변수에 값을로드하고, 그렇지 않으면 404 또는 생성 할 속성을 구성한 오류 동작을 반환합니다.

예를 들어 리소스 그림이 있고 특정 그림을 소유 한 사용자 만 그림의 이름을 편집 할 수 있습니다.

편집 작업이 있으므로 편집하려는 그림의 pictureId가 분명히 있습니다. load_and_authorize_resource는 현재 컨텍스트/사용자가 자원에 액세스 할 수 있는지 여부를 확인합니다.

Here은 모듈의 작은 비디오 소개입니다.

+0

RoR에 익숙하지 않은 사람들을 위해 그것을 당신이 비록 정의 Authorize 속성을 쓸 수있는 기능입니다 모방하려면 이 플러그인이 제공하는 기능은 무엇입니까? –

+0

이 업데이트되었습니다. 질문이 있으시면 알려주세요 – Karan

답변

2

ASP.NET MVC 용 플러그인의 존재를 알지 못합니다.

public class LoadAndAuthorizeResourceAttribute : AuthorizeAttribute 
{ 
    private class ModelDescriptor 
    { 
     public string Name { get; set; } 
     public Type ModelType { get; set; } 
    } 

    private const string ModelTypeKey = "__ModelTypeKey__"; 
    public override void OnAuthorization(AuthorizationContext filterContext) 
    { 
     var parameters = filterContext.ActionDescriptor.GetParameters(); 
     if (parameters.Length > 0) 
     { 
      // store the type of the action parameter so that we could access it later 
      // in the AuthorizeCore method 
      filterContext.HttpContext.Items[ModelTypeKey] = new ModelDescriptor 
      { 
       Name = parameters[0].ParameterName, 
       ModelType = parameters[0].ParameterType, 
      }; 
     } 
     base.OnAuthorization(filterContext); 
    } 

    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     var authorized = base.AuthorizeCore(httpContext); 
     if (!authorized) 
     { 
      // the user is not authenticated or authorized => no need to continue 
      return false; 
     } 

     // get the currently authenticated username 
     string username = httpContext.User.Identity.Name; 

     // get the id of the resource that he is trying to manipulate 
     // the id should be sent either as part of the query string or the routes 
     string id = httpContext.Request.RequestContext.RouteData.Values["id"] as string; 

     // get the action param type 
     var modelDescriptor = httpContext.Items[ModelTypeKey] as ModelDescriptor; 

     if (modelDescriptor == null) 
     { 
      throw new InvalidOperationException("The controller action that was decorated with this attribute must take a model as argument"); 
     } 

     // now load the corresponding entity from your database given the 
     // username, id and type 
     object model = LoadModel(id, username, modelDescriptor.ModelType); 

     if (model == null) 
     { 
      // the model that satisfies the given criteria was not found in the database 
      return false; 
     } 

     httpContext.Request.RequestContext.RouteData.Values[modelDescriptor.Name] = model; 

     return true; 
    } 

    private object LoadModel(string id, string username, Type modelType) 
    { 
     // TODO: depending on how you are querying your database 
     // you should load the corresponding model here or return null 
     // if not found 
     throw new NotImplementedException(); 
    } 
} 

을 지금이 속성들로 장식되어 컨트롤러 액션 가질 수있다 : 당신이 간략하게 요약 할 수

[LoadAndAuthorizeResource] 
public ActionResult Edit(Picture model) 
{ 
    ... if we get that far the user is authorized to modify this model 
} 
+0

달콤한! 감사! 언젠가는 앞으로이 프로젝트를 NuGet 패키지로 만들려고 노력할 것입니다. 다른 프로젝트에서도 유용 할 것입니다. :) – Karan

관련 문제