खुला हुआ बंद किया हुआ

Disable Swagger (Unless Authenticated?) #302


User avatar
0
robb बनाया था

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 उत्तर (ओं)
  • User Avatar
    0
    liangshiwei बनाया था
    सहायता दल 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 बनाया था

    Thank you for the information.

    In what file do we add this?

  • User Avatar
    0
    liangshiwei बनाया था
    सहायता दल Fullstack Developer

    Add to app.UseSwagger(); before

  • User Avatar
    2
    robb बनाया था

    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 v8.2.0-preview Updated on मार्च 25, 2024, 15:11