gjspaho
gjspaho

Reputation: 314

ServiceStack - prevent unauthorized access to static files

I understand there is more than one way of handling service authentication/authorization, but I cannot make it work for static files.

Is there a way of configuring the behavior to be the same as with services; if not authenticated a request to index.html should redirect to login page the same as a request to secured dto/service.

I am currently looking into RawHttpHandlers but since it is too early in the pipeline how do I get the authentication setup in the apphost config?

thanks in advance Gjergji

Upvotes: 3

Views: 388

Answers (1)

mythz
mythz

Reputation: 143369

You would have to use IAppHost.RawHttpHandlers because that's the only custom handler in ServiceStack's Request Pipeline that gets executed before the built-in static file handling is accessed.

But you should still be able to access the Users Session with the available extension methods, e.g:

this.RawHttpHandlers.Add(httpReq =>
{
    var isStaticFileRequest = httpReq.PathInfo.StartsWith("/static");
    if (isStaticFileRequest)
    {
        var session = httpReq.GetSession();
        if (!session.HasRole("TheRole"))
            return new ForbiddenHttpHandler();
    }
    return null;
});

This handler simply checks if it's a request for a static file, in this case the path info starts with /static, and if is checks the user session if they have the required role, if not it returns a Forbidden request, otherwise it returns null to tell ServiceStack to continue executing the request.

Note: if it's needed you can access any registered dependency from outside of ServiceStack with HostContext.Resolve, e.g:

var authRepo = HostContext.Resolve<IAuthRepository>();

Upvotes: 2

Related Questions