要將Swagger與現有的認證系統集成,您需要在ASP.NET Core項目中配置Swagger生成器以包含身份驗證信息。以下是一個簡單的示例,展示了如何將Swagger與JWT(JSON Web Token)認證集成:
首先,確保已安裝以下NuGet包:
在Startup.cs
文件中,導入以下命名空間:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
ConfigureServices
方法中,配置Swagger生成器以包含身份驗證信息:services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
// 添加JWT身份驗證
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme.",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});
});
Configure
方法中,啟用Swagger UI:app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
ConfigureServices
方法中添加以下代碼:services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://your-identity-provider";
options.Audience = "your-audience";
});
[Authorize]
屬性來保護需要身份驗證的API:[ApiController]
[Route("[controller]")]
[Authorize]
public class MyController : ControllerBase
{
// ...
}
現在,當您運行應用程序并訪問Swagger UI時,它將顯示一個“Authorize”按鈕,允許用戶輸入JWT令牌。在發送需要身份驗證的請求時,Swagger UI將自動將令牌添加到請求頭中。