Reputation: 65
I have a webservice using the old API. Almost all of my service handlers requires authentication and I therefore use the Authenticate attribute on the service level.
All my services implement a custom base service, which use OnBeforeExecute to populate some authentication related properties.
Is there a fast way to see if the handler for the current request requires authentication in the OnBeforeExecute method?
I would prefer not having to look through the attributes using reflection as I understand this to be a fairly slow operation. I also expect that the ServiceStack system already has this information somewhere in its belly :)
What I ended up doing:
Since my project has services where I use the ApplyTo argument of Authenticate to disable the auth requirement for some handlers, I ended up with the following.
protected override void OnBeforeExecute(TRequestDto request)
{
base.OnBeforeExecute(request);
var attr = FilterAttributeCache.GetRequestFilterAttributes(request.GetType()).OfType<AuthenticateAttribute>().FirstOrDefault();
if (attr != null)
{
ApplyTo reqmethod = base.Request.HttpMethodAsApplyTo();
if ((attr.ApplyTo & reqmethod) == reqmethod)
{
//
// do stuff that should only be done when
// the handler requires authentication
//
}
}
}
Upvotes: 2
Views: 170
Reputation: 143284
There is nothing special about the Authentication request filter attribute, other than it has the lowest priority so it's executed first.
ServiceStack does maintain a FilterAttributeCache of all attributes a Request DTO has, so you can use this API to determine if the AuthenticateAttribute is defined for a particular service, e.g:
var hasAuth = FilterAttributeCache.GetRequestFilterAttributes(request.GetType())
.OfType<AuthenticateAttribute>().FirstOrDefault() != null;
Upvotes: 2