【发布时间】:2019-10-02 07:47:34
【问题描述】:
我正在尝试将授权标头添加到 SwaggerUI api 测试中。下面是我的 Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "API",
Description = "QPIN API with ASP.NET Core 3.0",
Contact = new OpenApiContact()
{
Name = "Tafsir Dadeh Zarrin",
Url = new Uri("http://www.tdz.co.ir")
}
});
var securitySchema = new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
};
c.AddSecurityDefinition("Bearer", securitySchema);
var securityRequirement = new OpenApiSecurityRequirement();
securityRequirement.Add(securitySchema, new[] { "Bearer" });
c.AddSecurityRequirement(securityRequirement);
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
{
app.UseCors("Cors");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMiddleware<ApiResponseMiddleware>();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
授权按钮已添加到 Swagger UI 中,我已输入所需的访问令牌,如下所示
但问题是,当我想尝试 API 时,令牌没有被添加到 API 请求中,当我单击 API 上的锁定图标时,它显示没有任何可用的授权,见下文
【问题讨论】:
-
最好告诉您使用的是哪个版本的 Swagger (Swashbuckle)。您在控制台中收到任何错误吗?你可能想检查这个问题github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1197
-
这是我在 VS2019 (5.0.0.rc3) 中通过包管理器更新的最新版本(发布条件)。当我执行 API 时出现未授权错误,控制台中没有其他内容
标签: asp.net-core swagger asp.net-core-webapi swagger-ui .net-core-3.0