Determining Whether a User Is Authorized to Perform a Task

Microsoft Enterprise Library 5.0

DropDown image DropDownHover image Collapse image Expand image CollapseAll image ExpandAll image Copy image CopyHover image

A common security requirement is the need to authorize users to perform tasks. The Security Application Block helps by standardizing access to authorization providers such as the AzManAuthorizationProvider or the AuthorizationRuleProvider, or to authorization rules stored within the application configuration.

Typical Goals

In this scenario, you must determine if a user is authorized to perform a task, based on the user identity, role information, and any authorization rules that are specified.

Solution

Retrieve the identity, role, and rule information to be used for the user, and create a GenericPrincipal object for the user. Call the Authorize method of the authorization provider, passing to it the user's identity.

Using Authorize

The following code shows how to use the Authorize method. It assumes that you have resolved the IAuthorizationProvider type through the Enterprise Library container to obtain an instance of the authorization provider you want to use, and stored the reference in a variable named ruleProvider.


Note:
For more information on instantiating objects, see Creating and Referencing Enterprise Library Objects.


C# Copy Code
IPrincipal principal = new GenericPrincipal(new GenericIdentity("Username"), new string[]{"Manager"});

// Determine whether user is authorized for the rule defined as "Print Document".
bool authorized = ruleProvider.Authorize(principal, "Print Document"); 
Visual Basic Copy Code
Dim principal As IPrincipal = New GenericPrincipal(New GenericIdentity("Username"), New String() {"Manager"})

' Determine whether user is authorized for the rule defined as "Print Document".
Dim authorized As Boolean = ruleProvider.Authorize(principal, "Print Document") 

For information about resolving Enterprise Library objects in your applications, see Creating and Referencing Enterprise Library Objects.

Usage Notes

The Security Application Block is designed to use either the AzManAuthorizationProvider or the AuthorizationRuleProvider. With the authorization request, supply the context for authorization. Typically, this is an access request or a request to perform an action.