2016-06-13 1 views
0

나는 asp.net에서 지옥을 구성 할 때 내가 얻을 수있는 automagic을 탐구하는 방법을 이해하려고 노력하고있다. 저는 현재 asp.net web-api 2에서 asp.net 코어로 작은 api를 번역하고 있습니다. 나는이 구성에서 403이 어디서 오는지, 어떻게 고쳐야할지 모르겠습니다. 지금은 api 엔드 포인트의 대다수가 유효한 토큰을 필요로하기 때문에 토큰의 특정 클레임을 확인할 필요가 없습니다. 따라서 모든 인증 된 컨트롤러에 대해 유효한 베어러 토큰을 사용할 때 200이어야하는 403 응답을 얻습니다. 또한 지금은 Auth0와 함께 비대칭 키를 공급자로 사용합니다.JwtBearerAuthentication을 사용하여 403을 수정하는 방법은 무엇입니까?

Startup.cs configure 메소드 JWT 베어러 토큰의 유효성을 검사하는 데 사용하고 있습니다.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
    { 
     loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
     loggerFactory.AddDebug(); 
     //Middleware added here order matters 

     //TODO formatter settings https://docs.asp.net/en/latest/mvc/models/formatting.html 

     //samples to check 
     //https://auth0.com/docs/server-apis/webapi-owin 
     //https://github.com/auth0-samples/auth0-aspnetcore-webapi-rs256 
     var options = new JwtBearerOptions 
     { 
      Audience = Configuration["auth0:clientId"] 
      ,Authority = $"https://{Configuration["auth0:domain"]}/" 
      ,Events = new JwtBearerEvents() // just a pass through to log events 
     }; 

     app.UseJwtBearerAuthentication(options); 
     // Very hacky to catch invaild tokens https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/issues/191 
     // issue says the need for the required hack is fixed but it's been still happening. Issue about the fix https://github.com/aspnet/Security/issues/411 
     app.Use(next => async context => { 
      try 
      { 
       await next(context); 
      } 
      catch 
      { 
       // If the headers have already been sent, you can't replace the status code. 
       // In this case, throw an exception to close the connection. 
       if (context.Response.HasStarted) 
       { 
        throw; 
       } 
       context.Response.StatusCode = 401; 
      } 
     }); 
     app.UseMvc(); 

     // TODO global exception handling https://github.com/dotnet/corefx/issues/6398 
     app.UseSwaggerGen(); 
     app.UseSwaggerUi(); 
    } 

}

답변

0

그것은 당신의 토큰 미들웨어가 들어오는 요청을 검증하기 위해 실행되지 않는 것 같습니다. 토큰 미들웨어가 자동으로 실행되도록 설정해보십시오.

var options = new JwtBearerOptions 
    { 
     //other configurations.. 
     AutomaticAuthenticate = true; 
    }; 

또한 특성을 사용하여 컨트롤러에서 인증 체계를 지정할 수 있습니다.

[Authorize(AuthenticationSchemes = "MyAuthenticationScheme")] 

여기에 대해 자세히 알아보기 : Limiting identity by scheme

+0

AutomaticAuthenticate = true; 기본값은 – TealFawn

0

문제는 ConfigureServices 섹션의 정책이었다. 가장 간단한 정책은 내가 지금 필요한 모든 것입니다.

public void ConfigureServices(IServiceCollection services) 
    { 
     // Add framework services. 
     services.AddMvc(c => 
     { 
      // TODO implement this abstract class c.Filters.Add(typeof(ExceptionFilterAttribute)); 
      var policy = new AuthorizationPolicyBuilder() 
       .RequireAuthenticatedUser() 
       .Build(); 
      c.Filters.Add(new AuthorizeFilter(policy)); 
      c.Filters.Add(typeof(ValidateModelFilter)); 
     }); 
관련 문제