ServiceStack global request filter does not work

I have a global authentication request filter suggested by mythz (ServiceStack dev) in this SO answer

My filter:

RequestFilters.Add((httpReq, httpResp, requestDto) => { if (!PublicRoutes.Contains(httpReq.PathInfo)) { new AuthenticateAttribute().Execute(httpReq, httpResp, requestDto); } }); 

The filter does not work for me when I request ServiceStack Razor pages that inherit dynamic ViewPage

Example / Default.cshtml:

 @inherits ViewPage <!DOCTYPE html> <html> <head> <title>HOME</title> ... ... ETC 

At the bottom of the answer in the comments, the raiser question suggests similar behavior, but does not accurately describe how to reproduce, so I don't see a solution.

Is there a solution? Did I do something wrong?


UPDATE

I found that I can immediately declare attributes on my page:

 @using ServiceStack.ServiceInterface @inherits ViewPage @{ new AuthenticateAttribute().Execute(Request, Response, this); } <!DOCTYPE html> ... ... ETC 

Or I'm sure I can create a class that inherits ViewPage, and run them in the Init method and use the new class on the Razor pages.

Both of these solutions seem extraneous and not very dry.

+7
source share
2 answers

In the end, I created my own ViewPage class for this and calling filters after the model was installed on the page:

 public abstract class FilterViewPage<TModel> : ViewPage<TModel> where TModel : class { public override void SetModel(object o) { base.SetModel(o); this.AppHost.RequestFilters.ForEach(action => action.Invoke(this.Request, this.Response, this.Model)); this.AppHost.ResponseFilters.ForEach(action => action.Invoke(this.Request, this.Response, this.Model)); } } 

I guarantee that only top-level pages inherit this, and do not apply it to partial pages, so filters only work only once.

+1
source

Well, besides just checking that someone is logged in, most of the role-based content is handled for you based on the attributes of the DTO request. There are several options for what you are doing. Firstly, this is an empty dto that does nothing:

 [Route("/")] [Authenticate] public class Default { } public class DefaultService : Service { public object Get(Default req) { return new object(); } } 

The second is a simple check if the user is registered on the razor page

 @{ var session = Cache.SessionAs<AuthUserSession>(); if (!session.IsAuthenticated) throw new HttpException(403, "You are not logged in."); } 
0
source

All Articles