swagger ASP.NET核心2.0:在没有控制器的情况下验证路由

new9mtju  于 2022-11-06  发布在  .NET
关注(0)|答案(2)|浏览(215)

我已经在我的网站上添加了Swagger和Swashbuckle生成器,并跟随this tutorial。现在,当导航到https://localhost:port/swagger/时,我可以看到生成的API文档。注意,我没有创建任何SwaggerController类--这都是由NuGet包处理的。
问题是,我的整个站点,甚至是API,都是使用自定义LDAP进行身份验证的。我也想保护/swagger/页面。但是,我没有找到一种方法来做到这一点。StackOverflow上唯一相关的问题描述了adding authentication INTO swagger requests-不对整个API文档页面进行身份验证。
是否有一种特定的方法来保护生成的/swagger/页面?或者,是否有一种通用的方法来向ASP.NETCore2.0MVC路由添加身份验证验证器?

1bqhqjot

1bqhqjot1#

创建一个自定义的中间件处理程序,然后将其添加到管道中,如下所示:

启动.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseAuthorization();

            app.UseMvc();
            app.UseStaticFiles();

            //And here's where the middleware is registered
            app.UseRequestAuthHandler();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });
        }

中间件类:

namespace SwaggerDemo.Handlers
{
    using System.Net;
    using System.Threading.Tasks;

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Http;

    public class RequestAuthHandler
    {
        private const string _swaggerPathIdentifier = "swagger";
        private readonly RequestDelegate _next;

        public RequestAuthHandler(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            // First check if the current path is the swagger path
            if (context.Request.Path.HasValue && context.Request.Path.Value.ToLower().Contains(_swaggerPathIdentifier))
            {
                // Secondly check if the current user is authenticated
                if (!context.User.Identity.IsAuthenticated)
                {
                    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    return;
                }
            }
            await _next.Invoke(context);
        }
    }

    public static class RequestAuthHandlerExtension
    {
        public static IApplicationBuilder UseRequestAuthHandler(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<RequestAuthHandler>();
        }
    }
}
pbgvytdp

pbgvytdp2#

我想出了以下解决办法:(灵感来自Ryan的解决方案)

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using System;

/// <summary>
/// The extension methods that extends <see cref="IApplicationBuilder" /> for authentication purposes
/// </summary>
public static class ApplicationBuilderExtensions
{
    /// <summary>
    /// Requires authentication for paths that starts with <paramref name="pathPrefix" />
    /// </summary>
    /// <param name="app">The application builder</param>
    /// <param name="pathPrefix">The path prefix</param>
    /// <returns>The application builder</returns>
    public static IApplicationBuilder RequireAuthenticationOn(this IApplicationBuilder app, string pathPrefix)
    {
        return app.Use((context, next) =>
        {
            // First check if the current path is the swagger path
            if (context.Request.Path.HasValue && context.Request.Path.Value.StartsWith(pathPrefix, StringComparison.InvariantCultureIgnoreCase))
            {
                // Secondly check if the current user is authenticated
                if (!context.User.Identity.IsAuthenticated)
                {
                    return context.ChallengeAsync();
                }
            }

            return next();
        });
    }
}

如果您已正确设置了身份验证机制,则此操作会将用户重定向到登录页面。
然后,在构建应用程序时(例如,针对NSwag)

app.RequireAuthenticationOn("/swagger");
//Enable Swagger + Swagger Ui
app.UseSwaggerUi3WithApiExplorer(this.ConfigureSwagger);

相关问题