1

私はasp.netコア2.0で小さなWeb APIを作っています。私はJWTを使ってAPIのエンドポイントを保護しています。JWTがスローした例外をキャッチできません。

これは私がこれは私のStartup.csファイルですthis jwt bearer authentication

を使用しているJWTミドルウェアです:私は

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

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 
    } 

のコード行を使用することにより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

関連する問題