.net core 5 中的 Swagger 给我错误——没有指定 authenticationScheme,也没有找到 DefaultChallengeScheme

Swagger in .net core 5 give me the error --No authenticationScheme was specified, and there was no DefaultChallengeScheme found

当我从 Swagger UI 请求任何 API 端点时,出现以下错误

System.InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action configureOptions).

at Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, String scheme, AuthenticationProperties properties)

at Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)

at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)

at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)

at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)

at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)

at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS

=======

Accept: /

Accept-Encoding: gzip, deflate

Accept-Language: en-US,en;q=0.5

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySWQiOiIzIiwiTG9naW5JZCI6ImFkbWluIiwiVXNlclR5cGVJZCI6IjEiLCJFbWFpbCI6ImEiLCJNb2JpbGUiOiJhIiwianRpIjoiMWU1MDY3ODAtMWRjNS00MDYzLWFkMTktMDdlMjg4MzAxOWVjIiwiZXhwIjoxNjIzNDYzNjQ4LCJpc3MiOiJlZHVjYXJlLmNvbSIsImF1ZCI6ImVkdWNhcmUuY29tIn0.G2-D_oIdwUDw_3iz87jxWBIMabFpLlR5ASjCr109kNM

Connection: keep-alive

Host: localhost:21068

Referer: http://localhost:21068/swagger/index.html

Swagger配置如下

public void ConfigureServices(IServiceCollection services)
        {
services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "Edu Care API", Version = "v1" });

                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "Please insert the authorization token into field",
                    Name = "Authorization",
                    BearerFormat = "JWT",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.Http,
                    Scheme = "bearer"
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement {
                {
                    new OpenApiSecurityScheme
                    {
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id = "Bearer"
                    }
                    },
                    new string[] { }
                }
                });

            });
        }


 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Edu Care API v1");
                //c.RoutePrefix = string.Empty;
            });

app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();           

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapRazorPages();
            });

}

我的基本控制器如下

 [Authorize]
    [ApiController]
    [Route("api/[controller]")]
    public class BaseController : ControllerBase
    {

    }

我的API终点如下

[Route("api/[controller]")]
    [ApiController]    
    public class AcademicFeeConfigurationController : BaseController
    {

 [HttpGet]
        [Route("[action]")]
        public IActionResult GetFeeRelatedAllSli()
        {
            try
            {
                object sli = new
                {
                    FeeTypeSli = new FeeTypeService(context).FeeTypeSli(),
                    ClassInfoSli = new ClassInfoService(context).ClassInfoSli(),
                    SectionSli = new SectionInfoService(context).SectionInfoSli(),
                    AcademicSessionSli = new AcademicSessionInfoService(context).AcademicSessionSli(),
                };

                return Ok(sli);
            }
            catch (Exception ex)
            {
               
                ResponseModel.Notification = UtilityHelper.CreateNotification(Helpers.ExceptionMessage(ex), Enums.NotificationType.Error);
                return StatusCode(500, ResponseModel);
            }
        }
}

可能遗漏了什么。谁能给任何 suggestion/solution

这与 Swagger 无关,您的代码缺少 AddAuthentication()。下面的示例注册身份验证方案(JWT 和 Cookie),同时使用 JWT 作为默认方案。 Docuementation.

中的更多信息
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => Configuration.Bind("JwtSettings", options))
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => Configuration.Bind("CookieSettings", options));