asp.net-core - 如何使用登录页面保护 ASP.NET Core 2.2 Web Api Swagger?
问题描述
通过使用 swagger 的 netcore 2.2 web api 有什么方法可以在用户看到那些 api 文档之前保护我的 api 文档,然后他们会去登录>然后 api 文档。
更多的权力堆栈溢出。希望任何人都可以帮助..
解决方案
如果用户在想要访问 swagger 索引页面时未通过身份验证,您可以创建一个自定义中间件以重定向到登录:
public class SwaggerAuthorizedMiddleware
{
private readonly RequestDelegate _next;
public SwaggerAuthorizedMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
//Add your condition
if (context.Request.Path.StartsWithSegments("/swagger")
&& !context.User.Identity.IsAuthenticated)
{
context.Response.Redirect("/Identity/Account/Login");
await Task.CompletedTask;
}
else
{
await _next.Invoke(context);
}
}
}
public static class SwaggerAuthorizeExtensions
{
public static IApplicationBuilder UseSwaggerAuthorized(this IApplicationBuilder builder)
{
return builder.UseMiddleware<SwaggerAuthorizedMiddleware>();
}
}
在启动配置中:
app.UseAuthentication();
app.UseSwaggerAuthorized();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
推荐阅读
- javascript - Jquery 自动隐藏/关闭移动 div 导航菜单
- java - EdgeDriver (v81) 不再支持将 DriverService 作为参数传入
- python - 为什么 virtualenv 激活脚本代码从一个环境到另一个环境不同?
- javascript - jQuery 不能与 select 标签和 ngSwitch 一起使用,为什么?
- python - 使用 python 为同一个 url 发送多个 get 请求
- laravel - 扩展 Laravel 日志前缀以包含自定义环境变量
- xcode - 单击 RPSystemBroadcastPickerView 时显示异常
- java - 如何从 Java 中的 Arrays.sort 中获取已排序数字的索引?
- r - 添加对应于匹配列项的值
- xero-api - Xero-Api PKCE 授权返回“Invalid_grant”