如何在 .Net Core 的 Swashbuckle 上实现 JWT 令牌认证?
How to implement a JWT Token Authentication on Swashbuckle in .Net Core?
我在 Swagger UI/ Swashbuckle 中实现 JWT 令牌身份验证时遇到问题。
我在 Startup.cs
中实现了此代码作为文档中的示例。
方法中ConfigureServices
_ = services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Proyekto4Juan API",
Version = "v1"
});
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Please insert token",
Name = "Authorization",
Type = SecuritySchemeType.Http,
BearerFormat = "JWT",
Scheme = "bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement {
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[]{}
}
});
});
services.AddAuthorization(auth =>
{
auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser().Build());
});
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => Configuration.Bind("JwtSettings", options))
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => Configuration.Bind("CookieSettings", options));
并在 配置 方法上
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
_ = endpoints.MapControllers();
});
app.UseStatusCodePages();
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseSwagger();
app.UseSwaggerUI(c => {
c.DefaultModelExpandDepth(0);
c.DefaultModelsExpandDepth(-1);
c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 API test");
c.RoutePrefix = string.Empty;
});
}
但是当我使用 Swagger 在控制器上测试我的操作时 UI。
在端点上,我这样装饰我的动作。
[HttpPost]
[Route("DestroyUserSession")]
[Authorize]
public async Task<ResultModel> DestroyUserSession([FromBody] string userID)
{
//..... Do Something
}
我写了一个完整的JWT token生成和验证流程,可以参考如下:
我在 Swagger UI/ Swashbuckle 中实现 JWT 令牌身份验证时遇到问题。
我在 Startup.cs
中实现了此代码作为文档中的示例。
方法中ConfigureServices
_ = services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Proyekto4Juan API",
Version = "v1"
});
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Please insert token",
Name = "Authorization",
Type = SecuritySchemeType.Http,
BearerFormat = "JWT",
Scheme = "bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement {
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[]{}
}
});
});
services.AddAuthorization(auth =>
{
auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser().Build());
});
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => Configuration.Bind("JwtSettings", options))
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => Configuration.Bind("CookieSettings", options));
并在 配置 方法上
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
_ = endpoints.MapControllers();
});
app.UseStatusCodePages();
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseSwagger();
app.UseSwaggerUI(c => {
c.DefaultModelExpandDepth(0);
c.DefaultModelsExpandDepth(-1);
c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 API test");
c.RoutePrefix = string.Empty;
});
}
但是当我使用 Swagger 在控制器上测试我的操作时 UI。
在端点上,我这样装饰我的动作。
[HttpPost]
[Route("DestroyUserSession")]
[Authorize]
public async Task<ResultModel> DestroyUserSession([FromBody] string userID)
{
//..... Do Something
}
我写了一个完整的JWT token生成和验证流程,可以参考如下: