2014-08-27 6 views
0

웹 API 컨트롤러의 기본 컨트롤러에 적용되는 웹 API 인증 필터가 있습니다. 권한 유형은 기본입니다. 인증 필터는 IAutofacAuthenticationFilter를 사용하며 인증 및 인증을 수행하기 위해 자동 주입 된 일부 서비스를 사용합니다.WebApi 인증 필터

모든 것이 GET 요청에서 예상대로 작동합니다. 인증 헤더를 읽고 확인합니다. 요청에 권한 부여 헤더에 적절한 인증 정보가없는 경우, 요청은에 응답됩니다.

public void OnChallenge(HttpAuthenticationChallengeContext context) { 
    var host = context.Request.RequestUri.DnsSafeHost; 
    context.Request.CreateResponse(HttpStatusCode.Unauthorized, "Unauthenticated request"); 
    context.Request.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", host)); 
} 

그러나, POST 요청이 이루어질 때 모든 것이 동일한 방식이라고 예상대로 상기 방법이 호출되는하지만 요청 실제 제어 동작으로 이동하여 처리를 유지한다.

OnAuthorization이 수정되거나 오버로드되지 않았습니다. 대신

OnAuthenticate은 다음과 같다 :

protected virtual bool OnAuthorizeUser(KeyContainer name, string key, HttpActionContext actionContext) { 

     // get principal code ... 

     Thread.CurrentPrincipal = principal; 
     actionContext.RequestContext.Principal = principal; 
     if (HttpContext.Current != null) 
      HttpContext.Current.User = principal; 

     return true; 
    } 

권한 부여 필터는 다음과 컨테이너에 등록된다 : 여기

public void OnAuthenticate(HttpAuthenticationContext context) 
    { 


     var identity = ParseAuthorizationHeader(context.ActionContext); // identity is a custom object representing the information in the auth header 
     if (identity == null) { 
      HandleUnauthorizedRequest(context.ActionContext); 
      return; 
     } 


     if (!OnAuthorizeUser(identity.Name, identity.Key, context.ActionContext)) { 
      HandleUnauthorizedRequest(context.ActionContext); 
      return; 
     } 
    } 

이 주를 설정하고, 사용자를 인증하는 사용자 지정 방법 :

builder.Register(c => 
      new AuthorizeActionFilterAttribute(
       c.Resolve<IService>()) 
      .AsWebApiAuthenticationFilterFor<BaseApiController>() 
      .InstancePerRequest(); 

POST 요청에서 어떤 현상이 발생합니까? GET과 다른데 어떻게이 문제를 해결할 수 있습니까?

+0

OnAuthenticate 메서드에서 무엇을하고 있습니까? –

+0

@PeterLillevold 더 자세한 정보로 질문을 업데이트했습니다. 흥미로운 것은 Autofac에서 IAutofacAuthenticationFilter 인터페이스를 사용하지 않고'var dependecyScope = actionContext.Request.GetDependencyScope();를 사용하여 필요한 서비스를 해결하면 var lifetimeScope = dependecyScope.GetRequestLifetimeScope(); _ service = lifetimeScope.Resolve ()'를 호출하고 기본 api 컨트롤러를 필터로 꾸미면 문제가 사라집니다. – boosts

답변

2

문제가 InstancePerRequest 필터 등록과 같다고 생각합니다. fairly extensive FAQ on per-request scope usage이 있고 그 중 일부는 you can't have per-request dependencies in filters입니다. 왜냐하면 WebAPI는 컨트롤러가 만들어지면 필터 인스턴스를 캐시하기 때문입니다. 발견 한 작업을 성공적으로 수행하는 유일한 방법은 필터 자체에서 서비스 위치를 사용하는 것입니다. 불행히도 우리가 Autofac 측면에서 할 수있는 것은 없습니다. WebAPI에는 이러한 방식으로 동작 할 수있는 모든 것이 내장되어 있으며 재정의 할 수 없습니다.

바라 건데 그들은 ASP.NET vNext에서이를 바꿀 것입니다.

+0

캐싱이 GET 및 POST 요청에 모두 영향을 미치지 않습니까? 문제는 게시물 요청에 대해서만 발생합니다. 나는 FAQ를 체크 아웃 할 것이다. – boosts