要将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将自动将令牌添加到请求头中。