关闭门后的Swagger-UI中的ServiceStack API文档
我希望只有在我们的网络应用程序上对用户进行身份validation(表单身份validation)时才允许访问swagger-ui和元数据,但我希望一直允许API访问(API有一些公共方法,有些需要基本身份validation)。
所以我做的是为API添加了这个路由前缀:
public override RouteAttribute[] GetRouteAttributes(Type requestType) { var routes = base.GetRouteAttributes(requestType); routes.Each(x => x.Path = "/API" + x.Path); return routes; }
和:
ServiceRoutes = new Dictionary { { typeof(AuthenticateService), new[] { "/api/auth", "/api/auth/{provider}" } }, }
这也是在web配置中:
事情是,当我去/api/
now时工作正常,但是当我尝试调用某些方法时,我被重定向到我的login
路线。
有没有办法像我开始那样解决这个问题,或者有更好的方法来保护文档?
没有明确的选项要求在元数据页面上进行身份validation,但您可以使用PreRequestFilter来保护对/metadata
和/swagger-ui
页面的访问:
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(); } } });
如果您使用的是Swagger 2.0 / Open APIfunction ,则可以保护对/openapi
JSON规范的访问,您可以在运行时动态添加[Authenticate]
属性:
public AppHost() { typeof(OpenApiService) .AddAttributes(new AuthenticateAttribute()); }
如果您使用的是较旧的Swagger 1.2插件 ,则可以通过以下方式保护对后端服务的访问:
public AppHost() { typeof(SwaggerResource) .AddAttributes(new AuthenticateAttribute()); typeof(SwaggerResources) .AddAttributes(new AuthenticateAttribute()); }
这假设您使用的是ServiceStack身份validation而不是ASP.NET 身份validation。