阅读量:0
要将Swagger与现有的认证系统集成,您需要在ASP.NET Core项目中配置Swagger生成器以包含身份验证信息。以下是一个简单的示例,展示了如何将Swagger与JWT(JSON Web Token)认证集成:
首先,确保已安装以下NuGet包:
- Swashbuckle.AspNetCore
- Microsoft.AspNetCore.Authentication.JwtBearer
在
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"); });
- 确保已配置JWT身份验证中间件。在
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将自动将令牌添加到请求头中。