Adding RequiredPermissionAttribute at runtime

Hi ServiceStack,
I need to conditionally decorate (or not) a service with a RequiredPermissionAttribute depending on a condition known only at runtime.
Example
var type = typeof(HelloService);
if (conditionOccurs) {
type.AddAttributes(new RequiredPermissionAttribute(“PermissionToCallHelloService”));
}
Unfortunately this doesn’t work: I’m able to call my service also if conditionOccurs = true and I’ve not “PermissionToCallHelloService” permission (in my case I’m not even authenticated).
Is there some workaround?
Thanks

Any changes to Service Attributes need to be done before Configure() is called, either within the AppHost constructor or before appHost.Init() is called.

If that’s not possible, just do the permission check in code, e.g:

if (!this.GetSession().HasPermission("ThePermission", AuthRepository))
    throw HttpError.Forbidden("Permission deined");                   

Any changes to Service Attributes need to be done before Configure() is called, either within the AppHost constructor or before appHost.Init() is called.

In my case it’s not possible but I’ve found a solution injecting at runtime (after appHost.Init()) a global request filter like this:

// ...
var requiredPermission = new RequiredPermissionAttribute("Permission");

HostContext.GlobalRequestFilters.Add((req, res, requestDto) =>
{
   if ()
   {
      requiredPermission.Execute(req, res, requestDto);
   }
});

Thanks.

1 Like