Open Closed

Disable Swagger (Unless Authenticated?) #302


User avatar
0
robb created

We noticed that if you aren't logged in, if you hit /swagger, you get the full listing of API endpoints. We do not want to publish this. We would like to disable swagger. Preferably, swagger would still work if you are logged in as an admin user, but if that is too complicated we will consider simply disabling it. How can we do this?


4 Answer(s)
  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Hi,

    You can add a middleware to do it: like this:

    if (!env.IsDevelopment())
    {
        app.Use(async (httpContext, next) =>
        {
            if (httpContext.Request.Path.Value.ToLower().Contains("swagger"))
            {
                var user = httpContext.RequestServices.GetService<ICurrentUser>();
                if (user.IsAuthenticated && user.IsInRole("Admin"))
                {
                    httpContext.Response.StatusCode = 404;
                    return;
                }
            }
            await next.Invoke();
        });
    }
    
  • User Avatar
    0
    robb created

    Thank you for the information.

    In what file do we add this?

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Add to app.UseSwagger(); before

  • User Avatar
    2
    robb created

    Thanks, but for reference the above code is not quite correct. Return 404 if the user is NOT authenticated or is NOT a member of the admin role.

                app.Use(async (httpContext, next) =>
                {
                    if (httpContext.Request.Path.Value.ToLower().Contains("swagger"))
                    {
                        var user = httpContext.RequestServices.GetService<ICurrentUser>();
    
                        if (!user.IsAuthenticated || !user.IsInRole("admin"))
                        {
                            httpContext.Response.StatusCode = 404;
                            return;
                        }
                    }
    
                    await next.Invoke();
                });
    
Made with ❤️ on ABP v9.1.0-preview. Updated on November 01, 2024, 05:35