Swagger UI 403 发布后禁止生产

时间:2021-05-26 12:13:55

标签: asp.net-core swagger swashbuckle.aspnetcore

我在 Swashbuckle.AspNetCore WebApi 上安装了 6.1.4 Asp.Net 5.0

API 使用 Microsoft.AspNetCore.Authentication.JwtBearer 5.0.6 进行保护。

我添加了一个 LoginController 和一个 HTTPPOST 端点 [AllowAnonymous] 过滤器来生成初始 JWT。

在本地运行时,我可以使用 Swagger UI 调用它并生成令牌。但是,如果我发布到我们的预生产服务器进行进一步测试,我们在通过 swagger 调用登录端点时会收到 403 Forbidden 错误?不过我可以通过 Postman 成功调用它。

swagger ui 的配置如下 int eh Startup.cs;

   services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v2", new OpenApiInfo { Title = "Services.WebApi", Version = "v2" });

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);

                var securitySchema = new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\".",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.Http,
                    Scheme = "bearer",
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id = "Bearer"
                    }
                };

                c.AddSecurityDefinition("Bearer", securitySchema);

                var securityRequirement = new OpenApiSecurityRequirement
                {
                    { securitySchema, new[] { "Bearer" } }
                };

                c.AddSecurityRequirement(securityRequirement);
            });

然后在 Configure 方法中;

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();

        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
            app.UseHttpsRedirection();
            app.UseCors();
        }  
      
       app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v2/swagger.json", "Services.WebApi ASP NET Core 5 v2"));

谁能告诉我可能是什么问题?

编辑

我也可以确认,如果我通过postman生成一个JWT(到预生产服务器URL),然后把这个添加到UI顶部的Swagger UI授权中;

  1. 调用 HTTPGGET 端点之一返回成功
  2. 调用 POST api/login 端点仍然失败(尽管 JWT 已添加到其中)。

0 个答案:

没有答案
相关问题