2017-09-07 2 views
0

속성 [AllowAnonymous] 및 [AuthorizeAttribute]를 사용하여 액세스를 제어하는 ​​webapi가 있습니다. 또한 사용자 지정 특성을 만들어 일부 논리를 권한 부여에 추가했습니다. 웹 API가 인증을 위해 무기명 토큰을 사용하고 있습니다. 내 프로젝트에서 익명 요청을 허용하는 모든 작업을 수행 할 목적으로 설정 (InDemo라는 bool)이 있습니다. 즉, [AllowAnonymous] 특성을 가진 모든 작업처럼 작동합니다.데모 모드에서 모든 API 컨트롤러 요청 허용

OAuthOptions = new OAuthAuthorizationServerOptions 
      { 
       TokenEndpointPath = new PathString("/Token"), 
       Provider = new ApplicationOAuthProvider("self"), 
       AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(30000), 
       AllowInsecureHttp = true 
      }; 

      app.UseOAuthBearerTokens(OAuthOptions); 


public class CustomApiAuthorizeAttribute : AuthorizeAttribute 
{ 
    protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext) 
    { 
     if (Settings.Default.InDemo) 
      return true; 

     // ... more custom validations 
    } 
} 

이 좋은만큼 내 요청이 유효한 베어러 토큰을 포함로, 다음 IsAuthorized가 호출 작동하고 나는 사용자 정의 검증을 우회 할 수있다. 그러나 토큰이 유효하지 않으면 IsAuthorized는 호출되지 않으며 "이 요청에 대해 권한 부여가 거부되었습니다."라는 응답이 전송됩니다. 이제 InDemo가 true로 설정된 경우 토큰을 무시하고 싶습니다. 즉 [AllowAnonymous]가있는 것으로 동작합니다.

답변

0

좋아, 여기 어떻게 해결할 수 있습니다. CustomApiAuthorizeAttribute를 IAuthenticationFilter를 구현하고 항상 인증 된 컨텍스트 원리로 설정했습니다.

public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) 
    { 
     if (Settings.Default.AllowAnonymous) 
        context.Principal = new AuthenticatedPrincipal(Thread.CurrentPrincipal); 
    } 

    public class AuthenticatedPrincipal : IPrincipal 
    { 
     private readonly IPrincipal principalToWrap; 

     public AuthenticatedPrincipal(IPrincipal principalToWrap) 
     { 
      this.principalToWrap = principalToWrap; 
      Identity = new AuthenticatedIdentity(principalToWrap.Identity); 
     } 

     public bool IsInRole(string role) 
     { return principalToWrap.IsInRole(role); } 

     public IIdentity Identity { get; } 
    } 

    public class AuthenticatedIdentity : IIdentity 
    { 
     public AuthenticatedIdentity(IIdentity identityToWrap) 
     { 
      Name = identityToWrap.Name; 
      AuthenticationType = identityToWrap.AuthenticationType; 
     } 

     public string Name { get; } 
     public string AuthenticationType { get; } 

     public bool IsAuthenticated => true; 
    } 
관련 문제