'ServiceStack HasPermission in the context of the request

I am trying to harness the authentication and authorisation features of servicestack so that I don't need to pollute my service code with this, which should lead to cleaner tests etc.

In my application, a user has permission to do something in a certain context.

ie A user can only view products that are in their product set.

To accomplish this I thought about decorating my productViewRequest dto with a permission attribute called canView and then to create my own implementation of IAuthSession to check that the user is requesting a product within their allowed set.

Would this be a decent approach or am I barking up the wrong tree?

Assuming it is a correct approach, how do I go about getting the context ie the productViewRequest object in the HasPermission call on my session implementation?

Thanks for your help



Solution 1:[1]

First I would check the ServiceStack built-in auth options https://docs.servicestack.net/authentication-and-authorization

If that doesn't fit your requirements, a request filter attribute will give you access to the request context.

public class CanViewAttribute : RequestFilterAttribute {
    private readonly string permission;

    public CanViewAttribute(string permission) {
        this.permission = permission;
    }

    public override void Execute(IHttpRequest req, IHttpResponse res, object responseDto) {
        // todo: check permission
    
        if (!hasPermission) {
          res.StatusCode = (int)HttpStatusCode.Forbidden;
          res.EndRequest();
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mike W