簡體   English   中英

.net core 5 中的 Swagger 給我錯誤--No authenticationScheme is specified, and there was no DefaultChallengeScheme found

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

當我從 Swagger UI 請求任何 API 端點時,給我以下錯誤

System.InvalidOperationException:未指定 authenticationScheme,也未找到 DefaultChallengeScheme。 可以使用 AddAuthentication(string defaultScheme) 或 AddAuthentication(Action configureOptions) 設置默認方案。

在 Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext 上下文,字符串方案,AuthenticationProperties 屬性)

在 Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.HandleAsync(RequestDelegate 下一個,HttpContext 上下文,AuthorizationPolicy 策略,PolicyAuthorizationResult 授權結果)

在 Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext 上下文)

在 Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext 上下文)

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

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

在 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext 上下文)

標題

=======

接受: /

接受編碼:gzip,放氣

接受語言:en-US,en;q=0.5

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySWQiOiIzIiwiTG9naW5JZCI6ImFkbWluIiwiVXNlclR5cGVJZCI6IjEiLCJFbWFpbCI6ImEiLCJNb2JpbGUiOiJhIiwianRpIjoiMWU1MDY3ODAtMWRjNS00MDYzLWFkMTktMDdlMjg4MzAxOWVjIiwiZXhwIjoxNjIzNDYzNjQ4LCJpc3MiOiJlZHVjYXJlLmNvbSIsImF1ZCI6ImVkdWNhcmUuY29tIn0.G2-D_oIdwUDw_3iz87jxWBIMabFpLlR5ASjCr109kNM

連接:保持活動

主機:本地主機:21068

參考: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();
            });

}

我的基礎 controller 如下

 [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);
            }
        }
}

也許缺少一些東西。 任何人都可以提供任何建議/解決方案

這與 Swagger 無關,您的代碼缺少 AddAuthentication()。 下面的示例注冊身份驗證方案(JWT 和 Cookie),同時使用 JWT 作為默認方案。 文檔中的更多信息。

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => Configuration.Bind("JwtSettings", options))
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => Configuration.Bind("CookieSettings", options));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM