How to: Create a Custom Authorization Attribute
This topic demonstrates how to add a custom attribute for authorization. The WCF RIA Services framework provides the RequiresAuthenticationAttribute and RequiresRoleAttribute attributes. These attributes enable you to easily specify which domain operations are only available to authenticated users or users in a specific role. In addition to these two attributes, you can create an attribute that represents customized authorization logic and then apply the attribute to domain operations.
When you expose a domain service, the domain service is available to everyone on the network. You cannot assume that your client application is the only application that will access the domain service. You can use customized authentication attributes to restrict access to domain operations even when the domain operation is accessed outside of your client application.
In this topic you create a custom authorization attribute by creating a class that derives from AuthorizationAttribute and overriding the IsAuthorized method to provide your customized logic. You can use the IPrincipal parameter and the AuthorizationContext parameter to access information that may be required within your customized authentication code. The AuthorizationContext object is null on query operations.
To create a customized authorization attribute
-
In the server project, create a class that derives from AuthorizationAttribute.
-
Override the IsAuthorized method and add logic for determining authorization.
The following example shows a custom attribute named
RestrictAccessToAssignedManagersthat checks whether the authenticated user is the manager of the employee whoseEmployeePayHistoryrecord is being modified. -
To perform the customized authorization logic, apply the custom authorization attribute to the domain operation.
The following example shows the
RestrictAccessToAssignedManagersattribute applied to a domain operation.