The method proposed by @Nico will work.
An alternative, that arguably provides better encapsulation and flexibility is to use the ClaimsPrincipalPermissionAttribute
instead of the AuthorizeAttribute
. This is part of WIF, which is in theory the preferred framework for identity and authorization in .Net.
In this model, the ClaimsPrincipalPermissionAttribute
specifies the authorization context of the request, in terms of an Resource and Operation - that is it describes the request, not who can access it.
The actual authorization logic is then encapsulated in a custom ClaimAuthorizationManager
that is given the current user principal and the authorization context. It's job is purely to do the authorization check. The ClaimAuthorizationManager
can be controlled by configuration in the application web.config file.
This is all described here
http://msdn.microsoft.com/en-us/library/system.identitymodel.services.claimsprincipalpermissionattribute.aspx
Although I prefer this method I don't think there are very strong reasons to prefer one over the other. I think the advantage of this approach are:
- It provides better encapsulation
- It is more flexible
- It is called by the CLR rather than the MVC framework, meaning it will get called by unit tests or anywhere the decorated method is called
- It can be used imperatively as well as declaratively (
ClaimsPrincipalPermission.CheckAccess("Customer","Add"))
- It seems to be more aligned with the direction Microsoft are going
A disadvantage is
- It is .Net 4.5 only. If you are on .Net 3.5 or 4, then you would have to use the earlier version of WIF. It is very similar to the .Net 4.5 version (but not identical). The namespaces are
Microsoft.IdentityModel
instead of System.IdentityModel
As I say though, it is a mostly a matter of preference in my opinion.