1

asp.net 코어 2.0으로 작은 웹 API를 만들고 있습니다. 내 API 끝점을 보호하기 위해 JWT를 사용하고 있습니다.JWT가 던진 예외를 catch 할 수 없습니다.

mvcOptions.Filters.Add(new ApiExceptionFilter()); 

I :이 코드 줄을 사용하여

public class Startup 
    { 
     #region Properties 

     /// <summary> 
     ///  Instance stores configuration of application. 
     /// </summary> 
     public IConfigurationRoot Configuration { get; } 

     #endregion 

     #region Methods 

     /// <summary> 
     ///  Callback which is fired when application starts. 
     /// </summary> 
     /// <param name="env"></param> 
     public Startup(IHostingEnvironment env) 
     { 
      var builder = new ConfigurationBuilder() 
       .SetBasePath(env.ContentRootPath) 
       .AddJsonFile("appsettings.json", true, true) 
       .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true) 
       .AddEnvironmentVariables(); 
      Configuration = builder.Build(); 
     } 

     /// <summary> 
     ///  This method gets called by the runtime. Use this method to add services to the container. 
     /// </summary> 
     /// <param name="services"></param> 
     public void ConfigureServices(IServiceCollection services) 
     { 
      // Add entity framework to services collection. 
      var sqlConnection = Configuration.GetConnectionString("SqlServerConnectionString"); 
      services.AddDbContext<RelationalDatabaseContext>(
       options => options.UseSqlServer(sqlConnection, b => b.MigrationsAssembly(nameof(Main)))); 

      // Injections configuration. 
      services.AddScoped<IUnitOfWork, UnitOfWork>(); 
      services.AddScoped<DbContext, RelationalDatabaseContext>(); 
      services.AddScoped<IEncryptionService, EncryptionService>(); 
      services.AddScoped<IIdentityService, IdentityService>(); 
      services.AddScoped<ITimeService, TimeService>(); 
      services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); 

      // Requirement handler. 
      services.AddScoped<IAuthorizationHandler, SolidAccountRequirementHandler>(); 
      services.AddScoped<IAuthorizationHandler, RoleRequirementHandler>(); 

      // Load jwt configuration from setting files. 
      services.Configure<JwtConfiguration>(Configuration.GetSection(nameof(JwtConfiguration))); 
      services.Configure<ApplicationSetting>(Configuration.GetSection(nameof(ApplicationSetting))); 

      // Build a service provider. 
      var serviceProvider = services.BuildServiceProvider(); 
      var jwtBearerSettings = serviceProvider.GetService<IOptions<JwtConfiguration>>().Value; 

      // Cors configuration. 
      var corsBuilder = new CorsPolicyBuilder(); 
      corsBuilder.AllowAnyHeader(); 
      corsBuilder.AllowAnyMethod(); 
      corsBuilder.AllowAnyOrigin(); 
      corsBuilder.AllowCredentials(); 

      // Add cors configuration to service configuration. 
      services.AddCors(options => { options.AddPolicy("AllowAll", corsBuilder.Build()); }); 
      services.AddOptions(); 

      // This can be removed after https://github.com/aspnet/IISIntegration/issues/371 
      var authenticationBuilder = services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme); 

      authenticationBuilder.AddJwtBearer(o => 
      { 
       // You also need to update /wwwroot/app/scripts/app.js 
       o.SecurityTokenValidators.Clear(); 
       o.SecurityTokenValidators.Add(new JwtBearerValidator()); 
       o.TokenValidationParameters = new TokenValidationParameters 
       { 
        ValidAudience = jwtBearerSettings.Audience, 
        ValidIssuer = jwtBearerSettings.Issuer, 
        IssuerSigningKey = jwtBearerSettings.SigningKey 
       }; 
      }); 


      #region Mvc builder 

      // Construct mvc options. 
      services.AddMvc(mvcOptions => 
      { 
       mvcOptions.Filters.Add(new ApiExceptionFilter()); 
       ////only allow authenticated users 
       var policy = new AuthorizationPolicyBuilder() 
        .RequireAuthenticatedUser() 
        .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) 

#if !ALLOW_ANONYMOUS 
        .AddRequirements(new SolidAccountRequirement()) 
#endif 
        .Build(); 

       mvcOptions.Filters.Add(new AuthorizeFilter(policy)); 

      }) 
      .AddJsonOptions(options => 
      { 
       options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 
      }); 

#endregion 
     } 

     /// <summary> 
     ///  This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
     /// </summary> 
     /// <param name="app"></param> 
     /// <param name="env"></param> 
     /// <param name="loggerFactory"></param> 
     /// <param name="serviceProvider"></param> 
     public void Configure(IApplicationBuilder app, 
      IHostingEnvironment env, 
      ILoggerFactory loggerFactory, IServiceProvider serviceProvider) 
     { 
      // Enable logging. 
      loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
      loggerFactory.AddDebug(); 

      // Use JWT Bearer authentication in the system. 
      app.UseAuthentication(); 

      // Enable cors. 
      app.UseCors("AllowAll"); 

      // Enable MVC features. 
      app.UseMvc(); 
     } 

#endregion 
    } 

:

내가이 내 Startup.cs 파일입니다 this jwt bearer authentication

를 사용하고있어 JWT 미들웨어입니다 ASP.Net MVC 컨트롤러, 특성에 의해 던져 예외를 잡을 수 있습니다 ... 하지만 JWT에 의해 던져 예외를 잡을 수 없습니다.

authenticationBuilder.AddJwtBearer(o => 
      { 
       // You also need to update /wwwroot/app/scripts/app.js 
       o.SecurityTokenValidators.Clear(); 
       o.SecurityTokenValidators.Add(new JwtBearerValidator()); 
       o.TokenValidationParameters = new TokenValidationParameters 
       { 
        ValidAudience = jwtBearerSettings.Audience, 
        ValidIssuer = jwtBearerSettings.Issuer, 
        IssuerSigningKey = jwtBearerSettings.SigningKey 
       }; 

      }); 

아무도 도와 줄 수 있습니까?

+0

새 프로젝트 템플릿에있는 예외 처리 미들웨어를 살펴보십시오. UseExceptionHandler. 또한 당신이 갈고리 할 수있는 jwt 옵션에 대한 AuthenticationFailed 이벤트가 있습니다. – Tratcher

+0

나는 그것을 시도했지만 MVC 예외를 잡을 수있다. 내가 AuthenticationFailed 알아,하지만 어쨌든 세계적으로 또는 예외를 잡을 수 있을지 궁금해. – Redplane

+0

어디에 넣으셨습니까? UseAuthentication 전에 이동해야합니다. 동일한 예외가 다시 발생하면 재실행 버전을 사용할 수없는 것으로 보입니다. 직접 응답 과부하 중 하나를 사용해야합니다. – Tratcher

답변

0

당신은 접근을 처리 글로벌 예외를 사용하여 이러한 오류를 처리하는 글로벌 예외를 추가하려고 할 수 있습니다, 감사합니다. ASP.NET Core 요청 파이프 라인에서 예외 처리를위한 패키지 살펴보기 - JosephWoodward/GlobalExceptionHandlerDotNet

+0

설명에 따르면, 컨트롤러 예외에 대해서만 생각합니다. 나는 그것이 Jwt 무기명 미들웨어와 함께 작동한다고 생각하지 않는다 – Redplane

+0

첫 테스트! TDD :) –

+0

시도했지만 작동하지 않습니다. 컨트롤러 내에서 던져진 예외 만 잡을 수 있습니다. : '( – Redplane

관련 문제