jklemmack
jklemmack

Reputation: 3636

Require authentication for (almost) every request using ServiceStack

I am building an ERP using ServiceStack and have authentication wired in and working. However, I'd like to require authentication on basically every single route, DTO, or static page - except the Login page and supporting resources (CSS, images).

Is there a simple, centralized way of doing this? I could apply [Authenticate] to every DTO/route, but it'd be easy to miss one.

How can I require authentication for all requests, save some? I suspect a global request filter of some form, but I'm not sure how to start that.

Upvotes: 1

Views: 163

Answers (2)

mythz
mythz

Reputation: 143284

Right, the easiest way is to use a Global Request Filter:

GlobalRequestFilters.Add((req, res, dto) => {
    if (!req.IsAuthenticated())
    {
        res.StatusCode = (int) HttpStatusCode.Unauthorized;
        res.EndRequest();
    }
});

This will ensure all Service Requests are authenticated, to also validate non Service Requests handled by ServiceStack are authenticated you can use a PreRequestFilters instead:

PreRequestFilters.Add((req, res) => {
    if (!req.IsAuthenticated())
    {
        res.StatusCode = (int) HttpStatusCode.Unauthorized;
        res.EndRequest();
    }
});

Upvotes: 1

jklemmack
jklemmack

Reputation: 3636

@mythz's solution is the most correct, but in my situation I had some specific additional criteria I didn't originally ask. Namely, I wanted to permit Authenticate requests, and to redirect users to the login page. I am using a custom Authentication provider ServiceStack.Authentication.Azure, so I ended up with a 303 Redirect instead of 403 Fail (or, more appropriately, 401 Unauthorized) to make it work with my OAuth-style provider.

this.GlobalRequestFilters.Add((req, res, requestDto) =>
{
    if (!req.IsAuthenticated() && !(requestDto is Authenticate))
    {
        res.RedirectToUrl("/auth/aadgraph?redirect=" + req.RawUrl.UrlEncode());
        res.EndRequest();
    }
});

Upvotes: 1

Related Questions