0
내가 여기 ( https://github.com/aspnet/Security)

Asp.net 코어 2.0 JWT는 AllowAnonymous

Startup.cs

 /// <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(options => 
      { 
       options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; 
       options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; 
      }); 

      authenticationBuilder.AddJwtBearer(o => 
      { 
       // You also need to update /wwwroot/app/scripts/app.js 
       o.Authority = jwtBearerSettings.Authority; 
       o.Audience = jwtBearerSettings.Audience; 
       o.RequireHttpsMetadata = false; 

       o.SecurityTokenValidators.Clear(); 
       o.SecurityTokenValidators.Add(new JwtBearerValidator()); 

       o.Events = new JwtBearerEvents() 
       { 
        OnAuthenticationFailed = c => 
        { 
         c.NoResult(); 

         c.Response.StatusCode = 500; 
         c.Response.ContentType = "text/plain"; 
         if ("dev".Equals(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"))) 
         { 
          // Debug only, in production do not share exceptions with the remote host. 
          return c.Response.WriteAsync(c.Exception.ToString()); 
         } 
         return c.Response.WriteAsync("An error occurred processing your authentication."); 
        } 
       }; 
      }); 

      #region Mvc builder 

      // Construct mvc options. 
      var mvcBuilder = 
       services.AddMvc(mvcOptions => 
       { 
        //only allow authenticated users 
        var policy = new AuthorizationPolicyBuilder() 
         .RequireAuthenticatedUser() 
         .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) 
         .AddRequirements(new SolidAccountRequirement()) 
         .Build(); 

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

      // Add json configuration/ 
      mvcBuilder.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(); 
     } 
입니다 .NET 코어 2.0 JWT 베어러 인증을 사용하여 작은 새 프로젝트를 만들고있어

을 무시하지 않습니다

이러한 구성을 사용하면 웹 응용 프로그램에서 jwt를 사용할 수 있습니다. 내 요청, 인증 헤더를 전달하는 경우, ([AllowAnonymous] 속성 아래에 위치) 인증을 필요로하지 않는 API와

  • OnAuthenticationFailed :하지만, 나는 현재에 직면하고있어 한 가지입니다 이벤트가 발생합니다 (토큰이 감지되지 않음).

내 질문은 : 내 JWT 인증 자동 AllowAnonymous로 표시되는 방법 또는 컨트롤러을 무시 할 수 있습니까?

는 동시에 두 가지 인증이 코드와 JWT 및 기타 하나 하나를 추가되기 때문에 그것의,

답변

0

내 생각, 감사합니다.

var mvcBuilder = 
       services.AddMvc(mvcOptions => 
       { 
        //only allow authenticated users 
        var policy = new AuthorizationPolicyBuilder() 
         .RequireAuthenticatedUser() 
         .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) 
         .AddRequirements(new SolidAccountRequirement()) 
         .Build(); 

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

그냥 JWT를 유지하고 정책을 추가 할 경우이 예

services.AddAuthorization(options => 
       { 
        options.AddPolicy("CreateUser", policy => policy.AddRequirements(
        new UserLevelRequirement("Admin") 
       )); 
       }) 

당신은 두 번 인증을 구성 할 수없는 것 그것을 할 수 있습니다.

+0

OnAuthenticationFailed 예외가 여전히 발생합니다. ( – Redplane

0

OnAuthenticationFailed 이벤트는이 사건이 "text/plain"으로 응답 ContentType이을 설정합니다 때문에 API가 (406) 허용하지를 반환합니다 심해질 수있게됩니다 ;. 코드 c.Response.ContentType = "text/plain";c.Response.ContentType = "application/json";으로 변경할 수 있습니다.

관련 문제