gpt4 book ai didi

c# - 关闭门后 Swagger-UI 中的 ServiceStack API 文档

转载 作者:行者123 更新时间:2023-11-30 16:42:16 30 4
gpt4 key购买 nike

我只想允许访问 swagger-ui 和元数据,只有当用户在我们的网络应用程序上经过身份验证(表单例份验证)时,但我想一直允许 API 访问(API 有一些公共(public)方法和一些需要基本身份验证).

所以我所做的是为 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<Type, string[]> {
{
typeof(AuthenticateService), new[] { "/api/auth", "/api/auth/{provider}" }
},
}

这在网络配置中也是如此:

<location path="api">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>

问题是,当我转到 /api/ 时工作正常,但是当我尝试调用某些方法时,我被重定向到我的 login 路由。

有没有办法像我开始的那样解决这个问题,或者有更好的方法来保护文档?

最佳答案

没有明确的选项要求对元数据页面进行身份验证,但您可以使用 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 API Feature,则保护对 /openapi JSON 规范的访问您可以在运行时动态添加 [Authenticate] 属性:

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

如果您使用的是旧版 Swagger 1.2 Plugin您可以通过以下方式保护对后端服务的访问:

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

这假设您使用的是 ServiceStack Authentication不是 ASP.NET 身份验证。

关于c# - 关闭门后 Swagger-UI 中的 ServiceStack API 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47096577/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com