Swagger Access to Admin Role only

It’s the first time i’m expose to swagger and I think it’s great interface…
I was wondering if it’s possible that the swagger-ui interface can be configure too bee seen only by a specific Role (Admin)

I’m not sure I wan’t this UI available to the www, only partner I work with are relevant…
Is there a configuration switch I can enable ?

You can protect access to built-in resources using a PreRequest Filter: https://stackoverflow.com/a/47102309/85785

So you should be able to limit access to Admin users to the Swagger UI with:

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

And protect access to /openapi json metadata response by dynamcially adding a RequiredRole attribute in your AppHost constructor:

AppHost()
{
    typeof(OpenApiService)
        .AddAttributes(new RequiredRoleAttribute(RoleNames.Admin));
}
1 Like

What a flexible and easy to configure framework :grinning:

1 Like