2017-04-07 1 views
0

사용자가 AuthorizeAttribute 사용자 지정에서 매개 변수 사용 방법을 보여 줄 수 있습니까? 이처럼매개 변수 웹 API를 사용하는 사용자 지정 인증

:

[Authorize(Role="Admin,Supervisor")] 

[Authorize(User="Me,You")] 

[Authorize(Action="abc,def")] 

이 지금 내 코드와 나는 여기에 매개 변수를 추가하는 방법을 아직 어떤 생각을 가지고 있겠지. 당신이 Authorize의 기본 구현을 확장함에 따라

public class CustomAuthorizeAttribute : AuthorizeAttribute 
    { 
     ApplicationDbContext _context = new ApplicationDbContext(); 

     public override void OnAuthorization(HttpActionContext actionContext) 
     { 

      if (AuthorizeRequest(actionContext)) 
      { 

       return; 

      } 

      HandleUnauthorizedRequest(actionContext); 
     } 

     protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) 
     { 
      if (((System.Web.HttpContext.Current.User).Identity).IsAuthenticated) 
      { 
       actionContext.Response = new HttpResponseMessage() 
       { 
        StatusCode = HttpStatusCode.Unauthorized, 
        Content = new StringContent("You are unauthorized to access this resource") 
       }; 

      } 
      else 
      { 
       base.HandleUnauthorizedRequest(actionContext); 
      } 
     } 

     private bool AuthorizeRequest(HttpActionContext actionContext) 
     { 
      var action = actionContext.ActionDescriptor.ActionName; 

      var controller = actionContext.ControllerContext.ControllerDescriptor.ControllerName; 

      var currentUser = actionContext.RequestContext.Principal.Identity.GetUserId(); 

      var user = _context.Users.Join(_context.UserAccesses, x => x.RoleId, y => y.RoleId, (x, y) => 
      new { Id = x.Id, firstName = x.firstName, lastName = x.lastName, RoleId = x.RoleId, Controller = y.Controller, 
       Action = y.Action }).Where(z => z.Id == currentUser && z.Controller == controller && z.Action == action) 
       .SingleOrDefault(); 

      if (user != null) 
       return true; 
      else 
       return false; 

     } 
    } 

답변

0

, 당신은 [CustomAuthorize(Role="Admin,Supervisor")]를 사용해야합니다. 그러면 역할이 설정됩니다. 상속 된 AuthorizeAttribute 부모에 포함되어 있으므로 코드에서 직접 Roles 속성에 액세스 할 수 있습니다.

public override void OnAuthorization(HttpActionContext actionContext) 
    { 
     var roles = Roles; 
     if (AuthorizeRequest(actionContext)) 
     { 

      return; 

     } 

     HandleUnauthorizedRequest(actionContext); 
    } 
+0

내 customauthorize에서 매개 변수 역할에 액세스하려면 어떻게해야합니까 ?? 샘플 좀주세요. 아직 액세스 할 수있는 코드가 없습니다. –

+0

@KennethAvecilla '역할'을 할 수 있습니다. 직접 액세스 할 수 있습니다. 부모 클래스에 이미 정의되어 있으므로 – Shahzad

+0

나는 이해하지 못합니다. 명확하게 설명하거나 코드를 보여주십시오. 부디! –

관련 문제