ServiceStack API documentation in Swagger-UI behind the closed doors

后端 未结 1 351
没有蜡笔的小新
没有蜡笔的小新 2021-01-20 18:02

I want to allow access to swagger-ui and metadata only if user is authenticated (forms auth) on our web app, but I want to allow API access all the time (API have some publi

1条回答
  •  一生所求
    2021-01-20 18:38

    There's no explicit option to require Authentication on metadata pages but you can use a PreRequestFilter to protect access to the /metadata and /swagger-ui pages with:

    PreRequestFilters.Add((req, res) =>
    {
        if (req.PathInfo.StartsWith("/metadata") || req.PathInfo.StartsWith("/swagger-ui"))
        {
            var session = req.GetSession();
            if (!session.IsAuthenticated)
            {
                res.StatusCode = (int)HttpStatusCode.Unauthorized;
                res.EndRequest();
            }
        }
    });
    

    And to protect access to the /openapi JSON specification if you're using Swagger 2.0 / Open API Feature you can dynamically add the [Authenticate] attribute at runtime with:

    public AppHost()
    {
        typeof(OpenApiService)
            .AddAttributes(new AuthenticateAttribute());
    }
    

    If you're using the older Swagger 1.2 Plugin you can protect access to backend Services with:

    public AppHost()
    {
        typeof(SwaggerResource)
            .AddAttributes(new AuthenticateAttribute());
        typeof(SwaggerResources)
            .AddAttributes(new AuthenticateAttribute());
    }
    

    This assumes you're using ServiceStack Authentication not ASP.NET Auth.

    0 讨论(0)
提交回复
热议问题