我在 ReactJS 应用程序中创建了一个自定义 SwaggerUI (index.html) 文件,可以通过
myapplication.com/docs/swagger/index.html
访问该文件。由于路由经过/docs/
,因此采用STS认证。但是,SwaggerUI 从 /swagger/v1/swagger.json
端点获取数据,该端点当前不受保护,允许任何人在 myapplication.com/swagger/v1/swagger.json
访问它。如何在 .NET 8 中保护此端点?
我可以建议实施授权中间件之类的东西。示例实现:
public class AuthMiddleware
{
private readonly RequestDelegate _next;
public AuthMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var path = context.Request.Path;
// You can pick your own logic to decide if each swagger
// request should be protected or not.
if (path.Value.Contains("swagger"))
{
// Basic auth check, you would need most probably something more :)
if (!context.User.Identity.IsAuthenticated)
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return;
}
}
// Call the next delegate/middleware in the pipeline.
await _next(context);
}
}
并在您的应用程序中使用它
app.UseMiddleware<AuthMiddleware>();