.net core 簡單集成JWT報No authenticationScheme was specified, and there was no DefaultChallengeScheme found錯誤


           #region JWT 認證
            services
              .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
              //.AddCustomAuth(o => { })
              .AddJwtBearer(options => {
                  options.TokenValidationParameters = new TokenValidationParameters {
                      ValidIssuer = Configuration["JwtSetting:Issuer"],
                      ValidAudience = Configuration["JwtSetting:Audience"],
                      IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtSetting:SecurityKey"])),
                      // 默認允許 300s  的時間偏移量,設置為0
                      ClockSkew = TimeSpan.Zero
                  };
              });
            #endregion
            #region MVC修改控制器描述
            services.AddHttpContextAccessor();
            services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
            services.AddMvc(config => {
                config.RespectBrowserAcceptHeader = true;
                //注入MVC攔截器
                config.Filters.Add<ApiFilter>();
            })
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new ContractResolver())
            .AddJsonOptions(options => options.SerializerSettings.Converters.Add(new ChinaDateTimeConverter()))
            .AddFormatterMappings(options => options.SetMediaTypeMappingForFormat("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
            .AddFormatterMappings(options => options.SetMediaTypeMappingForFormat("jpeg", "image/jpeg"))
            .AddFormatterMappings(options => options.SetMediaTypeMappingForFormat("jpg", "image/jpeg"));
       #endregion

在ConfigureServices中  注冊JWT必須在注冊MVC之前 否則就會報No authenticationScheme was specified, and there was no DefaultChallengeScheme found錯誤

            app.UseAuthentication();
            app.UseMvc();

在Configure中  添加JWT驗證也必須在MVC之前,否則也會報錯。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM