Disallow anonymous access to all services

We want to disallow anonymous access to all servicestack services. We host servicestack inside IIS (.net core). Staticfiles don’t require authentication (like images/js/etc files)

Is this the best way to solve it?

        this.GlobalRequestFilters.Add((httpReq, httpResp, requestDto) =>
        {
            if (!httpReq.PathInfo.StartsWithIgnoreCase("/auth"))
            {
                new AuthenticateAttribute().Execute(httpReq, httpResp, requestDto);
            }
        });

The preferred and recommended approach is to decoratively annotate Services that need authentication with the [Authenticate] which will also show up in /metadata pages.

This implementation only looks at routes starting with /auth and doesn’t handle when Services are executed using the pre-defined route.

An alternative/safer approach is to check the [Route] on the Request DTO and check that it’s not configured with your /auth convention. You can check the Users Session on whether they’re authenticated or not, e.g:

this.GlobalRequestFilters.Add((req, res, requestDto) =>
{
    var nonAuthRequest = requestDto.GetType().AllAttributes<RouteAttribute>()
        .Any(x => !x.Path.StartsWith("/auth"));

    if (nonAuthRequest && !req.GetSession().IsAuthenticated)
    {
        res.StatusCode = (int) HttpStatusCode.Unauthorized;
        res.StatusDescription = "Unauthorized";
        res.EndRequest();
    }
});

Thanks.

ps. I copied the code from the documention http://docs.servicestack.net/authentication-and-authorization#using-a-global-request-filter

Cool thx for the pointer, since it’s about different places you can use the [Authenticate] attribute I’ve changed it to test the Request DTO, i.e:

GlobalRequestFilters.Add((req, res, requestDto) =>
{
    if (ShouldProtectRequest(requestDto)) 
    {
        new AuthenticateAttribute().Execute(req, res, requestDto);
    }
});