Share via


Determining Whether a User Is Authorized to Perform a Task

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

The latest Enterprise Library information can be found at the Enterprise Library site.

A common security task is to authorize users to perform tasks.

Typical Goals

In this scenario, you must determine when 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. Create a GenericPrincipal object for the user. Create an authorization provider by calling the static GetAuthorizationProvider method of the AuthorizationFactory. Call the Authorize method of the authorization provider.

QuickStart

For an extended example of how to use the Authorize method with the AuthorizationRuleProvider to determine whether a user is authorized to perform a task, see Walkthrough: Determine Whether a User Is Authorized to Perform a Task.

Using Authorize

The following code shows how to use the Authorize method.

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

IAuthorizationProvider ruleProvider = AuthorizationFactory.GetAuthorizationProvider("RuleProvider");

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

Dim ruleProvider As IAuthorizationProvider = AuthorizationFactory.GetAuthorizationProvider("RuleProvider")

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

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.

The code shown above uses a factory class in the Security Application Block to obtain an instance of the authorization provider it requires. As an alternative, you can use the Unity Integration approach to create instances of the objects in the Security Application Block. For more details of the integration of Enterprise Library and the Unity Application Block, see Creating Objects Using the Unity Application Block.