Let\'s say that you have a .net web api with a GetResource(int resourceId) action. This action (with the specified id) should only be authorized for a user associated with t
You need to externalize your authorization. You want to move your entire authorization logic to a separate layer or service.
There are several frameworks - in different languages - that let you do that. In the .NET world, as suggested in the other answers, you have Claims-based authorization. Microsoft has a great article on that here.
I would advocate you go for a standardized approach, namely XACML, the eXtensible Access Control Markup Language. XACML gives you 3 things:
If we revisit your example, you would have something along the lines of:
public Resource GetResource(int id)
{
var resource = resourceRepository.Find(id);
if (isAuthorized(User.Identity,resource))
{
throw new HttpResponseException(HttpStatusCode.Unauthorized);
}
return resource;
}
public bool isAuthorized(User u, Resource r){
// Create XACML request here
// Call out to PDP
// return boolean decision
}
Your PDP would contain the following rules:
The benefit of XACML is that you can grow your authorization rules / logic independently of your code. This means you don't have to touch your application code whenever the logic changes. XACML can also cater for more parameters / attributes - for instance a device id, an IP, the time of the day... Lastly, XACML isn't specific to .NET. It works for many different frameworks.
You can read up on XACML here and on my own blog where I write about authorization. Wikipedia also has a decent page on the topic.