Designing Application-Managed Authorization

xiaoxiao2021-03-06  66

Designing Application-Managed Authorization

Related Links

Patterns and Practices INDEX

Chris Schoon, Doug Rees, Edward JezierskiMicrosoft Corporation

December 2002

Summary

This guide provides guidelines for designing and coding application-managed authorization for single or multi-tier applications that are based on Microsoft® .NET. It focuses on common authorization tasks and scenarios, and it provides information that helps you choose the best approaches and techniques THIS Guide is intended for architects and development.

This guide assumes that readers have a basic knowledge of topics such as Windows authentication and authorization, XML Web services, and .NET remoting. For more information about designing distributed .NET-based applications, see "Designing Applications and Services" in the MSDN® Library. For more information about designing security into distributed applications, see "Building Secure ASP.NET Applications" in the MSDN Library. For more general design guidance, see the .NET Architecture Center in Microsoft TechNet.

Download

Click Here to Download this Guide in PDF Format.

Contents

This Guide Includes The Following Sections:

Introduction

· Understanding Authorization

· Designing Authentication for Authorization

· Designing Identity Flow for Authorization

Performing Authorization In an Enterprise Application

· Creating Authorization Code with .NET Role-Based Security

· Reusing Authorization IMPLEMENTATIONS

· Appendix

Introduction

This guide describes how to perform authorization in .NET-based applications It explains the term authorization and discusses several mechanisms for performing authorization This guide also describes:.. · Important concepts such as identities and principals.

· How to use role-based security to authorize a category of users who share the Same security privileges.

· Significant Differences Between .Net and COM ROLE-BASED Security.

THE SPECIFIC Authorization Mechanism You Adopt OffenDs On How You Authenticate, or Verify The Identity of, Users. This Guide Examines:

· The Differences Between Windows Authentication and Non-Windows Authentication.

· How The Authentication Mechanisms Affect Authorization.

HOW to Flow Identity Information For Authorization Purposes To Remote Application Tiers.

In a typical enterprise application, you need to perform different kinds of authorization at each tier in the application. To help you to identify the need for authorization in each tier and to choose appropriate authorization strategies in various scenarios, this guide describes typical authorization tasks in The user interface tier, the business tier, and the data tier. Figure 1 Highlights Issues in each tier in an enterprise application.

Figure 1. Performing Authorization in Each Tier in an Enterprise Application

The .NET Framework Class Library Provides a Variety of Interfaces and class That Help You Perform Authorization with .Net Role-Based Security. THIS Guide Describes:

· Several Techniques for Checking WHETCILAR Belongs to a Particular Role. · How to handle authorization errors.

· Specific Authorization Issues That Arise In Multithreaded .NET Applications.

Much of the effort you invest in defining an authorization framework can be reused multiple application. This guide controls by describing:

How to define a reusable authorization framework.

· Guidelines on how to maximize the security and performance of such a framework.

Note This guide pertains to application managed authorization using features of the .NET Framework. The Authorization Manager API and Microsoft Management Console (MMC) snap-in available in the Windows® Server 2003 family of operating systems provide applications with a complete role-based access control framework. The Authorization Manager API, also known as AzMan, provides a simplified development model in which to manage flexible groups and business rules and to store authorization policies. For more information, see "Authorization Interfaces" and "Authorization Objects" in the MSDN Library.

Understanding Authorization

Authorization is confirmation that an authenticated principal-a user, a computer, a network device, or an assembly-has permission to perform an operation. Protection allows only appointed users to perform certain actions, and it prevents malicious acts.

This Section of The Guide Describes:

· The Protection That Authorization Provides.

· Basic authorization.

· The Authorization Capabilities of the .net framework.

Mitigating security threats

Authorization alone is not enough to secure an application; therefore, this guide briefly mentions the types of threats that face your application Some of the common security threats are as follows; these threads are often referred to by the acronym STRIDE They include:. ·. Spoofing Identity-An Unauthorized User Impersonating a Valid User of the Application

· Tampering with data-an attacker illegally changing or destroying data

· REPUDIABILITY-THE ABILITY OF A User to Deny That He or She Performed An Action

· Information disclosure-sensitive data released to users or to locals this sales not available to it

· Denial of Service-Acts of Sabotage That Make Applications Unavailable To Users

· Elevation of Privilege-a User Illegally Gaining An Unacceptables High Level of Access To the Application

You can use such techniques as The Following to Address Stride THREATS:

· Authentication-Strong authentication helps mitigate identity spoofing. When a user logs on to Windows or starts an application, he or she enters information in the form of credentials, such as a user name and password. Windows uses a protocol such as NTLM or Kerberos to validate the user's credentials and to log the user onto the system. Applications often use the product of a system logon or implement custom authentication as a basis for authorization. for more information about authentication, see "Building Secure ASP.NET Applications" in the MSDN Library.

· Authorization-Use the authorization techniques described in this guide to prevent data tampering and information disclosure threats. · Identity flow-Applications deployed across multiple computers sometimes need to pass information representing the identity of the authenticated user among the computers of the system. Identity flow is typical when authentication occurs on the first computer and other application logic resides on a separate computer. for more information about identity flow, see "Designing Identity Flow for Authorization" later in this guide.

· Auditing-A record of both authorized and unauthorized operations reduces repudiability. This guide does not describe auditing in detail. For more information about auditing, see "Building Secure ASP.NET Applications" in the MSDN Library.

For More Information About Stride, See "Designing for Securability" in the msdn library.

Figure 2 Shows A Model for How To MitiGate Stride Security Threats in a Multi-Tiered Application.

Figure 2. Model of a secure multi-tiered coplication

. Figure 2 depicts a multiple physical tier deployment; however, many smaller applications are implemented on one physical tier, simplifying authentication, authorization, and identity flow Figure 2 illustrates the following measures to mitigate security threats:

.

2. Encryption enables secure communication.

3. Authentication Prevents Identity Spoof.

4. Authentication Verifies Credentials Against a Data Store.5. Identity Flows Between The Application Tiers (Optional).

6. Auditing reduces repudiability.

7. Authorization Prevents Data Tampering and Exposure THREATS.

Selecting Authorization Mechanisms

You can use various authorization mechanisms to control the functionality of your applications so that they behave as intended and can not be misused either accidentally or deliberately These authorization mechanisms fall into one of the following categories.:

• SYSTEM Authorization-Windows Protects Resources Such AS Files and Stored Procedures with Access Control Lists (ACLs). Acls Specify Which Users Are Allowed to Access Securable Resources.

· .NET Code Access Security Authorization-Code access security authorizes code to perform actions based on the code's origin. For example, code access security determines which assemblies can access other assemblies in a .NET-based application, based on evidence criteria.

· Application Authorization-The Application Code Itself Authorzes User Actions.

Use a combination of these approaches to create A Secure Application, AS Shown in Figure 3.

Figure 3. Selecting Authorization Mechanisms

System Authorization

System authorization is the process of setting resource permissions or ACLs for objects that the operating system controls, such as printers and files System administrators maintain these settings System authorization is a yes or no decision:.. A user is either authorized or not authorized to access The resource.

Examples of System Authorization Include:

· Authorization settings in Microsoft ASP.NET-BASED Applications That Limit Access To URL Files Or Paths Specified In Web.config Files. Permissions Set In The Active Directory® Directory Service.

· NTFS File System Access Control Entries.

· Message Queuing Permissions.

• Permissions Grand Wtem Products Such AS Microsoft SQL ServerTM. Such Permissions Might Involve Individual Objects Such as Tables or Views.

For More Information About System Level Security and Authorization, See "Building Secure ASP.NET Applications" in the msdn library.

System Authorization Applies Constraints To Individual Objects; However, .Net Code Access Security Authorization Is Necessary To Contrain The Code.

.NET Code Access Security Authorization

. The .NET common language runtime uses code access security to constrain executable code Code access security works by granting permissions (known as permission sets) to application code based on evidence This evidence can include the code's origin, its publisher;. Or other evidence, Such as an assembly's strong name.

Permission Sets Let You Control What The Application CAN Perform, Such as Deleting Files OR Accessing The Internet. For Example, You Can Limit The Application To Use Only Isolated Storage Or To Control Access To Printing.

Code access security takes the evidence into account regardless of the user's identity. Even if a user with administrative privileges uses the application, the code access security permissions remain the same. For example, if the code comes from the Internet, limits-such as the Capacity to Delete Files-Apply Regardless of WHO The user is.examples of code access security usage include:

Preventing a Downloaded Component from Performing Dangerous ActionS by Limiting ITS Power and Placing It in An Iscolated Environment. Isolation Helps Prevent Rogue Code from Compromising Your System.

.

Limiting The Power of Your Components to Prevent Malicious Code from Misusing Them.

Note Use Caspol.exe or the Microsoft .NET Framework Configuration Management Console To Configure Code Access Security.

For More Information About Code Access Security, See The.NET Framework Developer's Guide Article "Code Access Security" in the msdn library.

CODE Access Security Helps Secure Your System By Checking Permissions for the Code, But Depending On The Application, You Might Also Need To Use Application Authorization To Check Permissions for the user.

Application Authorization

Most applications implement different functionality or security permissions, depending on the user interacting with the system. Design application authorization to limit access to application resources or to implement business rules based on the user's role within the application.

The primary purpose of application authorization is to secure functionality and other intangible items, such as business logic. For this reason, application authorization is difficult to implement with current system-level technologies because these technologies tend to use settings, such as ACLs, on physical . resources For example, you might want to secure an operation that approves an expense claim from an employee, but there is no physical resource to secure; therefore, when you design application authorization, you should focus on high-level operations rather than on individual resources.Application authorization provides an alternative approach to system authorization when system authorization mechanisms are too finely grained, or when they do not take into account application data or state. for example, system level security standards for XML Web services are still under development and AreateFore Still Evolving. You do not need to wait untric The Standards Are Complete To Add S ecurity to or create secure XML Web services. For XML Web services you build today, you can implement application authorization and use Secure Sockets Layer (SSL) or other combinations to secure calls to the service.

Examples of Application Authorization INCLUDE:

Checking WHETHER A User Has Permissions To Perform Specific ActionS-for Example, Approving An Expense Claims.

Checking WHETHER A User Has Permission To Access Application Resources-for Example, Retrieving Sensitive Column from a database.

You Will Learn How To Design and Code these Types of Application Authorization Later In this Guide.

Checking at the Gate

To prevent an operation from needlessly continuing to the point of failure, always authorize a user's request as soon as you can. Each point of authorization is called a gatekeeper. Examples of gatekeeping mechanisms include file and URL authorization in an ASP.NET gate. There may be several gatekeepers as the identity flows down through the tiers. Checking at the gate reduces the number of authorization checks necessary deeper in the system (past the entry point, or gate) .Objects that perform authorization checks deeper in the system have fewer requirements .

USING ROLES for Authorization

The .NET Framework Provides a role-based application Authorization Capability. A role is a category or set of users who share the Same security privileges.

Using Roles Rather Than Specific User Identities Provides The Following Benefits:

.

................... ..

.

Defining Roles Based on the Business Organization

Roles CAN represent the position the user holds in an organization; for example:

· Manager

· Employee

· ClaimApprovalDepartmentA benefit to this approach is that the information is generally retrieved from a store such as in Active Directory. Often these roles are useful in modeling actual business requirements.

Achieving Independence from Organizational Changes

You can also use roles to indeicate the Type Operations That A User Performs for His or Her Job. Such Roles Allow You to Link Application Functions to Individual Users; for Example:

· CanApproveClaim

CanaccessLab

CANVIEWBENEFITS

This second approach is flexible because you can design the roles around application functionality rather than around organizational structures. It might be harder to maintain because of a lack of infrastructure in which to store these roles. An application needs a combination of approaches in most cases.

Performing Authorization Without Using Roles

Sometimes you must base authorization on who the user is rather than on the roles he or she plays within the application. For example, you might allow only a direct manager to approve an employee's expense claim. You can achieve this finer level of authorization by comparing The Current User To The Manager of The Employee Who Filed The Claim.

USING ROLE-BASED Security In .Net-Based Applications

The .NET Framework provides a role-based security implementation in the System.Security.Principal namespace, which you use for application authorization. To work with application authorization in the .NET Framework, create IIdentity and IPrincipal objects to represent users. An IIdentity encapsulates ......................................

Figure 4. RELATIONSHIP BETWEEN IIDENTINTINTINTIN iPRINCIPAL OBJECTS

Notice The Following Points in Figure 4:

.

2. The IIdentity interface has the properties Name, IsAuthenticated, and AuthenticationType. Classes that implement IIdentity often contain additional private members specific to their purpose. For example, the WindowsIdentity class encapsulates the account token for the user on whose behalf the code is running.

3. An IPrincipal object is an instance of a class that implements IPrincipal. The IPrincipal object is a combination of an IIdentity representing the user and any roles he or she has. This allows for a separation of authentication and authorization capabilities.

4. The iprincipal object is used to perform.

Working with Identities

The .NET Framework Provides Four Classes That Implement The iIdentity Interface:

Windowsidentity

GenericIdentity

· PassportIndentity

· Formsidentity

Each class enables you to work with different kinds of user identities To access the current WindowsIdentity object for an application that uses Windows authentication, use the static GetCurrent method of the WindowsIdentity class, as the following code shows.:

Windowsidentity CurrentIndIndity = WindowsIdentity.getCurrent ();

You can also create custom identity classes by implementing the IIdentity interface in your custom class. For more information about creating custom identities, see "Extending the Default Implementation" later in this guide. For more information about how to work with the default IIdentity implementations own , SEE "Designing Authentication for Authorization" Later in this Guide.

Working with Principals

The .NET Framework provides the IPrincipal interface to link user roles and identities. All managed code that performs application authorization should use an object of a class that implements IPrincipal. For example, the WindowsPrincipal and GenericPrincipal classes provide inbuilt implementations of IPrincipal. Alternatively, you CAN CREATE YOUR OWN CUSTOM Principal Classes based on iPrincipal.

To make your coding more efficient, link the IPrincipal object to the current thread by using techniques described in the Designing Authentication for Authorization section later in this guide. Linking the IPrincipal object to the thread provides the current thread easy access to the IPrincipal object by using The Static CurrentPrincipal Property of The Thread Object, as The Following Code Shows:

WindowsPrincipal CurrentPrincipal = (WindowsPrincipal)

Thread.currentprincipal;

You can then perform an authorization check by testing whether the user is a member of a particular role You do so by using the IsInRole method of the IPrincipal interface, as the following code shows:. Bool roleMemberFlag = Thread.CurrentPrincipal.IsInRole (

"CanApproveClaims");

ASP.NET applications handle IPrincipal objects differently than do other .NET-based applications. ASP.NET creates the appearance of a session over the stateless HTTP protocol. As a part of this session, the IPrincipal object representing the user is available from the User property of the HttpContext object for all code executing the user's request. The common language runtime automatically updates Thread.CurrentPrincipal with the HttpContext.User value after the OnAuthenticate event of the Global.asax file.

ASP.NET Applications Offen User Property To Perform Authorization Checks, As The Following Code Shows:

Bool rolememberflag = context.user.isinrole ("canApproveClaims");

Note Manually changing HttpContext.User automatically updates the Thread.CurrentPrincipal for all threads executing within the same HTTP context. However, changing the Thread.CurrentPrincipal does not affect the HttpContext.User property. It affects only the chosen thread for the remainder of the request .

For more information about creating your own IPrincipal types, see "Extending the Default Implementation" later in this guide. For more information about how to work with the default IPrincipal implementations, see "Designing Authentication for Authorization" later in this guide.

Granting Permissions to Work with iIdentity and iPrincipal Objects

The ability to work with IIdentity objects is a sensitive operation because user-related information is available. Allowing applications to change the current IPrincipal object should also be protected because application authorization capability is based on the current principal. The framework provides this protection by requiring that these operations have a code access security permission. Grant the SecurityPermissionAttribute.ControlPrincipal permission to applications that need to manipulate these objects by using Caspol.exe or the .NET Framework Configuration tool.By default, all locally installed applications have this permission because they run under The full trust permission set.

Executing The Following Methods Require The ControlPrincipal Permission:

AppDomain.SetthreadprincipalPolicy ()

· Windowsidentity.getcurrent ()

· Windowsidentity.impersonate ()

Thread.currentPrincipal ()

For More Information About Setting Security Permissions Using Caspol, See "Configuring Security Policy Tool (Caspol.exe)" in the msdn library.

Managing Authorization Differences Between Windows and The Common Language Runtime

The common language runtime has a separate security infrastructure on top of the Windows security infrastructure. A Windows thread has a token for a Windows authenticated user, whereas the runtime thread has an IPrincipal object to represent the user.

. When developing your code, you must therefore consider at least two security contexts that represent a user For example, consider an ASP.NET-based application using forms authentication: The ASP.NET process runs under a Windows service account (a user account created specifically for an application) named ASPNET by default. Imagine a user named Bill logs on to the Web site. The Thread.CurrentPrincipal property represents the Forms authenticated user, Bill. The common language runtime sees the thread running as Bill, so any managed code sees Bill as the principal. If the managed code requests access to a system resource such as a file, the unmanaged code sees the ASPNET Windows service account regardless of the Thread.CurrentPrincipal value. Figure 5 represents these relationships.Figure 5. The authorization relationship Between Common Language Runtime and Operating System Threads

Impersonation allows you to change which user account the operating system thread executes under in its interactions with Windows. You can impersonate a Windows identity by calling the WindowsIdentity.Impersonate method. This form of impersonation allows you to access local resources as a particular user. When you call the Impersonate method, you will be logged on as the user that the WindowsIdentity represents. you must have access to the user's credentials on the server and call the LogonUser API. However, creating the WindowsIdentity manually can be complex, so you should perform Impersonation Only When IT IS ABSOLUTELY Necessary.

. The WindowsImpersonatationContext.Undo method reverts a user's identity back to the original identity after the application code impersonates another user These functions are generally called in a matched pair as the following code shows: // Impersonate a Windows identity

WindowsimpersonationContext ImpersonationCTX =

Windowsidentity.impersonate (useertoken);

// Do Something Under The Context of the Impersonated User

// REVERT to the user's real identity

Impersonationctx.undo ();

For More Information About Impersonating A Windows Account, See "Impersonating and Reverting" in The Msdn Library.

Note On Windows 2000, a process must have the SE_TCB_NAME privilege to call LogonUser API For more information about validating user credentials, see article Q180548,. "HOWTO: Validate User Credentials on Microsoft Operating Systems," in the Microsoft Knowledge Base.

Designing Authentication for Authorization

Authorization depends on authentication-that is, a user or process must be authenticated before it can be authorized to view or use protected resources This section of the guide examines two authentication mechanisms and explains how each affects authorization.:

Performing Authorization Based On Windows Authentication

Performing Authorization Based On Non-Windows Authentication

Your choice of authentication mechanism is often influenced by factors unrelated to authorization, such as the availability of Windows user accounts and general environmental considerations, including the client's browser type. However, the authentication choice you make does affect the way you perform your authorization checks.

Performing Authorization Based on Windows AuthenticationAll applications execute under a Windows user account known as the Windows identity. During Windows authentication, you use this Windows user account or the role to which the Windows user belongs to perform your authorization checks. Windows chooses the user account based On Credentials Supplied by One of the Following Techniques:

Using Information Supplied by The User When Hele OR She Logged On To The Computer

· Using a service account this you create especially for the application by Using Configuration Tools Such As the Component Services Management Utility

The Overall Process for Using Authorization With Windows Authentication IS:

. 1. Windows uses NTLM or Kerberos to validate the user's credentials For more information about using Kerberos delegation, see "How To: Implement Kerberos Delegation for Windows 2000" ". Building Secure ASP.NET Applications" in

2. The Successful Logon Produces A Windows Access Token, Which A WindowsIdentity Encapsules for .NET Applications.

3. Usually, the runtime automatically sets the Thread.CurrentPrincipal property to a WindowsPrincipal object that contains the Windows notion of roles; however, in some situations you must set it yourself as described later in this section.

4. Authorization Can Now Take Place Using Thread.currentPrIncipal.

5. When you call application logic remotely, there are some situations in which you need to manually provide the identity to the callee. This issue is described in greater detail in the Implementing Manual Identity Flow section later in this guide.Note Link the IPrincipal object to the thread, and then retrieve the principal or identity information from the Thread.CurrentPrincipal property. This allows you to maintain the role collection in memory and therefore reduce how often you need to look up this information.

Performing Authorization By Using Windows Roles

You can check to see whether a user is a member of specific Windows user groups (such as " / Users") by using a WindowsPrincipal object. The WindowsPrincipal object has an Identity property, which returns a WindowsIdentity object that describes the identity Of the current user.

You can configure .NET-based applications hosted within ASP.NET to have automatic access to a WindowsPrincipal from the Thread.CurrentPrincipal property by enabling Windows authentication in Web.config. You can use this technique in ASP.NET Web applications, XML Web Services And .NET Remoting Objects Hosted within asp.net.

Other .Net-Based Applications, Such As Windows Services, Console, And Windows Forms-based Applications, Require You to Establish Thread.currentprincipal Using ONE Of The Following Approaches:

Calling setprincipalPolicy

· Setting CurrentprIncipal

Note Code that works with IIdentity and IPrincipal objects requires the ControlPrincipal permission. Use code access security to grant this permission to the application. For more information, see "Using Role-Based Security in .NET-Based Applications" earlier in this guide.Calling SetPrincipalPolicy

The SetPrincipalPolicy method of the AppDomain object links specific types of IPrincipal objects to the application domain Use the WindowsPrincipal value of the PrincipalPolicy enumeration to link the current WindowsPrincipal object to the application threads, as the following code shows.:

Appdomain.currentDomain.SetPrincipalPolicy (PrincipalPolicy.Windowsprinc)

IPAL);

The principal is then available for authorization checks. Call SetPrincipalPolicy at the beginning of your application's execution to ensure that the IPrincipal object is linked to the threads before you perform any authorization checks.

DO NOT USE SetPrincipalPolicy WITHIN ASP.NET Applications Because Asp.Net Authentication Manages this value for you during the application_authenticaterequest Event Handler Defined in Global.asax.

Note SetPrincipalPolicy IS Effective Only If No Default Principal Exists for the Application Domain.

Setting CurrentPrIncipal

To set the CurrentPrincipal property, you must first create a new WindowsPrincipal object by passing a WindowsIdentity object to the WindowsPrincipal constructor You can then link the new WindowsPrincipal to the Thread.CurrentPrincipal property as the following code shows.:

Thread.currentprincipal = new windowsprincipal (WindowsIdentity.getCurrent ());

The apprincipal object is the the available for authorization checks.

For Information About How To Perform Authorization Checks with A WindowsPrincipal, See "Performing Authorization Checks" Later in this guide.performing authorization by using application-defined Roles

To create authorization checks based on application-defined roles (such as CanApproveClaims) you must manually create a generic or custom IPrincipal object. You do not need to call the SetPrincipalPolicy method because its default setting is NoPrincipal, which is the correct setting for assigning your OWN Principal.

Most of the time, create a GenericIdentity object based on the name of the authenticated user. (To get this name, use the Name property of the IIdentity interface.) This avoids any security issues involving the user's logon token-accessible using a WindowsIdentity object -When presenting the iidity Object to Other Components. You'S CREATE A GenericPrincipal That Links The iIdentity Object To Your List of Application-Defined Roles.

The Following Code Shows How To create GenericIdentity and genericprincipal objects when Use Windows Authentication:

GenericIdentity Identity = New

GenericIdentity (WindowsIdentity.getCurrent (). Name);

Thread.currentPrincipal = new genericprincipal (Identity,

New string [] {"canApproveClaims", "user"});

In most cases, retrieve the application-defined roles from a data store rather than hard-coding the roles. This allows you greater flexibility in assigning role membership. For an example of this approach, see "How to Build a GenericPrincipal Using SQL Server" In the appendix.

For Information About How To Perform Authorization Checks with a GenericPrincipal, See "Performing Authorization Checks" Later in this Guide.

Performing Authorization Based on Non-Windows AuthenticationYou might not want to or be able to use Windows authentication for application authorization. This could be because the users do not have Windows user accounts or because technical constraints keep you from using Windows authentication to validate the user's credentials .

Non-Windows authentication is the process of verifying the user's credentials using a technology other than Windows. This type of authentication includes those provided to you by the .NET Framework, such as ASP.NET Forms authentication and those you create yourself.

The Overall Process for Using Authorization with non-windows authentication is:

1. The Application Gathers The User Credentials.

2. The Application Verifier The Credentials, Typically Against a Custom Data Store Such as a SQL Server Database.

3. Initially, the Thread.CurrentPrincipal property is set to a GenericPrincipal object that does not contain any roles. You replace Thread.CurrentPrincipal with a new GenericPrincipal object, or with an object of a custom class that implements IPrincipal to provide application-defined roles .

4. Authorization Can Now Take Place Using Thread.currentPrIncipal.

5. WHEN CALLING Application Logic Remotely, You Might Need To Manually, The Identity To The Callee.

Common Types of Non-Windows Authentication INCLUDE:

· ASP.NET Forms authentication-ASP.NET Forms authentication automatically creates a FormsIdentity object that represents the validated identity. It contains a FormsAuthenticationTicket, which contains information about the user's authentication session.

The Forms authentication provider creates a GenericPrincipal based on the FormsIdentity object but with no role membership.For information about how to use ASP.NET Forms authentication, see article Q301240, "HOW TO: Implement Forms-Based Authentication in Your ASP.NET Application by Using C # .NET, "In The Microsoft Knowledge Base.

Forms authentication almost always uses credentials that are specific to your application For an example of how to verify Windows credentials obtained using forms authentication, see article Q316748, "HOW TO:. Authenticate Against the Active Directory by Using Forms Authentication and Visual C # .NET, "in the Microsoft Knowledge Base.

· Passport authentication-ASP.NET applications can use .NET Passport to perform authentication. Passport authentication produces a PassportIdentity object to represent a user identity. The PassportIdentity object extends the basic IIdentity interface to include Passport profile information.

.

For More Information, See "The Passport Authentication Provider" in the msdn library.

· ISAPI authentication solutions-An alternative approach is to implement a manual or custom authentication mechanism using HTTP headers such as the authentication mechanisms found in Microsoft Commerce Server. For more information about security in Microsoft Commerce Server, see "Commerce Server Security" in the MSDN Library.

The HTTP transport provides information (such as a cookie) for use in constructing a generic or custom IIdentity object and a generic or custom IPrincipal object.For more information about the authentication techniques available in ASP.NET, see "Authentication in ASP.NET: .NET Security Guidance "in The MSDN Library.

All the previously listed types of non-Windows authentication involve GenericPrincipal objects or custom IPrincipal objects. For an example of how to link a GenericPrincipal to application defined roles, see "How to Build a GenericPrincipal Using SQL Server" in the Appendix.

Designing Identity Flow for Authorization

Authentication creates IIdentity and IPrincipal objects for authorization purposes and determines how you can programmatically pass the identity information to application logic deployed remotely on other computers The propagation of an authenticated identity is known as identity flow There are two ways to achieve identity flow..:

Automatic Identity Flow

· Manual Identity Flow

Using Automatic Identity Flow

The common language runtime automatically provides identity flow when all of the code that requires the identity executes in the same context. The caller and callee are in the same context when they share the same application domain. If the client code (referred to as the caller ) and the component being called (referred to as the callee) are running within the same context, .NET automatically uses the same Thread.CurrentPrincipal object for both the caller and the callee. for cases in which the callee and caller execute on different threads See "Performing Authorization with Multiple Threads" later in this chapter.

EXAMPLES OF CODE EXECUTININ A SINGLE Application Domain include: • an ASP.NET Web Site That Contains All of the Required Code forin In-Process Components and Has No Remotely Deployed Logic.

· A Standalone Windows Forms-based Application With no remotely deployed logic.

Implementing Manual Identity Flow

Implement manual identity flow when authorization checks occur in a remote tier that can not perform authentication because of technical constraints. An example of this situation is calling a remote component using .NET remoting over the TCP channel. For more information about using channels in .NET Remoting Applications, See "Microsoft .NET Remoting: a Technical Overview" in the msdn library.

If you are implementing your own identity flow, pass the data in a manner that differs from the way you call your code (known as out-of-band). If your component interface involves calling functions and passing data using parameters, plan to send Identity Information Some Other Way.

For example, if you are calling an XML Web Service using SOAP, do not send the identity information as part of the message body;. Put it in a custom SOAP header This is not so much a security consideration as a code design issue. A separation like this enables extensibility, reuse, and aggregation of your code interfaces. This also allows you to change the way you send the identity information as technological standards evolve without changing your interface contract. The Web Services Security (WS-Security) specification demonstrates THIS.

Note that identity flow is different from passing credentials (which is effectively a reauthentication on the server). Alternatively, you can pass the credentials within the message itself-as long as you encrypt the credentials. However, the encryption would involve using a shared secret Key OR a public key system, in which case passing the credentials in this manner isn't Much of an advantage.following area some best practices for importing identity flow:

· Use the strongest Authentication Available Within The Functional Requirements and With Technology Constraints.

· Some identity flow techniques involve storing and / or passing secret information that is critical for the security of the identity flow mechanism. Encrypt the secret information or use a secure channel to keep the information safe. The classes in the System.Security.Cryptography namespace .

· Store Secret Information SecureLy Using A Technology Such as The Data Protection API (DPAPI). For Information About DPAPI, See "Windows Data Protection" in The Msdn Library.

Ensure That Your Implementation Allows You To Use Auditing to The Depth Required. For Information On Auditing, See "Monitoring and Auditing for End Systems" in Microsoft TechNet, ENS.

Passing Identity Information In a trusted environment

In a trusted environment, the callee leaves the responsibility of authentication to the caller. Any information passed from the caller to the callee is considered to be safe and reliable-for example, when a Web tier is the caller and a component on an internal application farm is the callee.Note This can be an insecure solution if it is possible for a rogue user to invoke code passing in another (and potentially fake) identity. to protect against these types of spoofing attacks, use technologies provided by the system layer to Secure The Communication Channels with Secure Sockets Layer (SSL) OR IP Security (IPSec), and Use Code Access Security To Ensure That Only Appropriate Code Calls your functions.

There Are Two Main Ways to Pass Identity Information Between Your Application Tiers in A Trusted Environment:

· Passing only the user name-The caller can pass only the user name to the callee. The callee can then query the authorization store to create a generic or custom IPrincipal object and attach it to the thread, as described earlier in this guide.

This approach is also used when you want to flow the identity to more information, see "Performing Authorization In The Data Tier" Later In this Guide.

This Approach Provides Flexibility, Because You Are Not Forcing Callers to Pass A Particular Type Of Object or Extra Information

· Passing the roles (using an IPrincipal object) -After authenticating the user, the caller can pass the roles to the callee by serializing the generic or custom IPrincipal object. The callee can then deserialize the object and attach it to the thread, as described earlier in this guide. This provides a similar effect to what happens automatically in a single application domain.Passing a custom IPrincipal object allows you to pass the roles and any extra information that a custom IPrincipal object could contain (such as user profile information), As well as the identity.

However, you can not pass IPrincipal objects that encapsulate certain types of information. For example, you can not pass a WindowsPrincipal or any other principal based on a WindowsIdentity object because the identity maintains a token that makes no sense outside of the original environment.

For More Information About Serializing An Iprincipal Object, See "How to Enable Authorization In a .NET Remoting Component" in the appendix.

Note Passing identity information is acceptable only if you are within a trusted environment using a secured communication channel, such as a corporate LAN protected from the outside by a firewall. Protect yourself from spoofs caused by intercepting or modifying network data on the wire.

Passing Identity Information In A Non-Trusted Environment

A non-trusted environment is one in which the caller does not trust the callee. In a non-trusted environment, the callee must validate the caller before performing authorization-for example, a Web application validating each request by a browser.

There are two common ways to pass identity information between your application tiers in a non-trusted environment:. · Passing signed data-Passing cryptographically signed data using public key infrastructure can be an effective means of identity flow You typically use this approach with asynchronous communication Because there is no session for automation.

Passing signed data works by including a digital signature with the message. The digital signature is computed using the private key of the sender and the contents of the message. To verify, the callee obtains the public key of the sender through a key management system and .

The .NET Framework provides the SignedXml class as an implementation of the XMLDSIG standard. This standard does not address issues such as key management or the trusting of keys. A receiver can make no assumptions about the trustworthiness of the keys used in this process. .

For sample code showing how to use the SignedXml class, see the CAPICOM SDK; CAPICOM is a Microsoft ActiveX® control that provides a COM interface to Microsoft CryptoAPI This sample code illustrates the full round trip of using a certificate authority, signing, and verifying. . an XMLDSIG signature You can find the sample code in the Platform SDK Redistributable:. CAPICOM 2.0 in the samples / c_sharp / xmldsig directory For more information about CAPICOM, see the "CAPICOM Reference" in the MSDN library.

· Passing a token-Passing a token involves passing a piece of information that the callee verifies to determine who the user is.Passing a token requires a shared authentication mechanism or a way to determine whether the token is valid. Passing a token might include passing a Kerberos ticket between components. Another example is a session cookie for an e-commerce Web site that an Internet Information Services (IIS) application creates upon authentication. The cookie passes back to the Web server each time the browser makes a call. This is Typical of Isapi Solutions.

Now that you understand how authorization works with the various authentication mechanisms and how to pass authorization data across tiers, you need to see how authorization works in each of the three tiers in an enterprise application.

Performing Authorization in an Enterprise Application

Most of today's applications benefit from a multi-tier design because multiple tiers provide scalability, flexibility, and performance enhancements. Although the purpose of authorization is essentially the same within each of the application tiers-that is, to control user access to system functionality and Data-You Design and Implement Authorization Differently Across The Tiers. The Three Tiers in An Enterprise Application Are The:

User Interface Tier

Business Tier

· Data Tier

Performing Authorization In The User Interface Tier

. This section describes how to perform authorization in the user interface tier The following topics are included later in the guide: Performing Authorization in the Business Tier and Performing Authorization in the Data Tier.

Performing application authorization in the user interface tier helps to ensure that only authorized users can view or alter data or perform business functions that are restricted to specific jobs (for example, salary-related activities). Authorizing users in the user interface tier is the first Opportunity You Have to Restrict Access To Processes That Require Authorization In Other Tiers Wtem The System.create Access Checks in The User Interface Tier When You NEED TO:

· Enable and disable or show and hide controls based on the user's role membership. For more information, see "Altering the controls on a form" later in this section.

· Change the flow from one form (or page) to the next, based on the user's role membership. For more information, see "altering the point flow" later in this section.

FOLLOW THEST PRACTICES WHEN You Create Autface Tier:

· Configure system authorization to control entry to the user interface whenever possible. For example, configure the Web.config file in an ASP.NET application to grant access to the entry page to only authorized users. For information about ASP.NET URL authorization, See "Building Secure ASP.NET Applications" in The MSDN Library.

· Defend against the user accessing the user interface elements at an incorrect stage in the process or task by authorizing the user when each form or page loads. For example, a user may need to fill out multiple Web pages in an ASP.NET application before an operation can be completed. Allowing the user to type a URL directly into the browser may allow the user to access pages he or she is not entitled to view at a certain stage. Therefore, you should perform application authorization checks when each page loads. · Do not base the security of your system exclusively on application authorization within the user interface. Perform additional access checks at the business or data tier because you might call these components in several ways or from different applications.

IF The User Interface Limits The Data The User CAN View, Don't Read Unnecessary Data from The Data Source; This Prevents Any Potential Leak of The Restricted Data As It Travels Around The Network.

Note All code samples in the following topics show Web Forms for the examples. You can modify the code to work in Windows Forms by changing User.IsInRole to Thread.CurrentPrincipal.IsInRole. For more information about the IsInRole method and performing authorization checks, see "Performing Authorization Checks" Later in this Guide.

Altering The Controls on A Form

In both Windows forms and ASP.NET applications, you may need to alter the way that you display controls in the user interface based on authorization. These changes include changing the visibility of some controls or disabling them.

For example, in an employee expense claims application, members of the CanApproveClaims role need a button in the form for approving claims All users not in this role do not see the Approve button The following code demonstrates this approach:.. If (User.IsInRole ("CanApproveClaims"))))

cmdapprove.visible = true;

Else

Cmdapprove.visible = false;

SUCH SIMPLISTIC Approaches Can Result in Long "IF-THEN-ELSE" CHAINS WHEN You CREATE Autfaces Or for Interfaces With Many Role Customizations.

Use the folload techniques to lessen the complexity of displaying controls based on Authorization Checks:

· Consolidate the logic-Place the logic for altering controls inside a private method that you call from within the form's Load event. Therefore, you have only one location to maintain the form authorization logic related to displaying controls.

The Following Code Shows How you can this approach to a Web form:

Private Void Page_Load (Object Sender, System.EventArgs E)

{

CONFIGUREControls ();

}

Private void configureControls ()

{

// Configure the form controls

}

• Use A Repeater Control WHICH A Control Corresponds To Multiple Lines of Data, Use a Repeater Control So That You CAN Modify All The Controls Settings At One Time.

For Example, if you create a Web Form button A Templated Column In The Form of a check box to allow authorized users to approve Multiple Claims at The Same Time.mo.At

The Following Code Shows How you can use this technique to display an appprove column in a datagrid.

Private void configureControls ()

{

//Modify the Visibility of the Templated Check Box Column // Based on The Role of The User

User.Isinrole ("canApproveClaims"))

Claimgrid.columns [3] .visible = true;

Else

Claimgrid.columns [3] .visible = false;

}

· Use a Model View Controller pattern-The Model View Controller pattern helps you separate the logic that controls the behavior of the user interface elements from the events fired by those controls. In the claims example, a form may have a list box of employees and a Show Claims button. You can enforce a clear separation of logic by putting all the code that should execute when ShowClaims is pressed in another function (called a controller function), or even in another class. The list box acts as a view on the employee data, and the Show Claims button handles user actions (such as a click) and calls the related controller function. The controller function is a method on your Web or Windows form that contains the logic to change the state of the business data and user Interface.

In the event handler.

· Use separate forms for each role-Create separate forms for each role if your number of roles is low and each role requires a significantly different version of a form. Test for role membership in each form and redirect to the correct form. This may add Significant Test Effort-useing the model view controller pattern as described earlier may help you factor out and reuse your presentation code.

Altering the page flow

Sometimes-such as in a typical wizard user interface-you want the user to complete multiple forms (or pages) to perform a business process, depending on his or her role membership. This approach can change the page order or flow.In the claims example, a GeneralManager member can view and approve claims from any employee in any department;. however, a StoreManager member can view claims from only employees in his or her department to allow the GeneralManager member to choose the department, create an extra step to retrieve This Information Before Displaying The Employe Selection Form.

. The following code shows one way to create this type of page flow The code uses the ASP.NET Server.Transfer method to transfer control to a different page The calls to Server.Transfer are wrapped within a private method named DisplayNextPage.:

Private void btnview_click (Object Sender, System.EventArgs E)

{

DisplayNextPage ();

}

Private void displaynextpage ()

{

User.Isinrole ("GeneralManager")))

Server.Transfer ("choosedEPartment.ASPX");

Else IF (User.Isinrole ("STOREMANAGER"))

Server.Transfer ("ChooseemPloyee.aspx");

}

Performing Authorization in The Business Tier

Business processes range from fairly simple business logic to larger, long-running workflows consisting of many trusted and nontrusted partners. Your business tier code must ensure that all client requests meet the authorization and logic rules that the organization prescribes.

Create Access Checks in The Business Tier When You NEED TO:

· Authorize an Operation That Performs a Business Process.

· Authorize a call from an external, nontrusted source before calling an internal business component. To do so could involve establishing an IPrincipal object for use by your business process in authorization. Use a service interface to manipulate the identity as it flows into your process, authorize a call to an internal business component, or both. · Authorize calls to other parts of your distributed system or external services that are not part of your application. to do so could involve manipulating the identity flow out from your component. Use a service Agent to make Sure The Current User CAN Perform The External Call and / or manipulate the Identity As It Flows Out of Your Process.

FOLLOW THEST PRACTICES WHEN CREANIZATION CODE IN TIER:

· Factor Authorization Capabilities Into Framework and Utility Components SUCH AS CUSTOM IPRINCIPAL OBJECTS. This allows you to create Authorization Capabilities Independent of the Business Logic.

.

However, To Produces A Secure Solution, Perform Authorization Wtem, Each Publicly Accessible Method Because, etc. To these Methods May Not Have Passed An Authorization CHECK.

Using role-based security in .net vs. COM

COM is best known for providing your applications with enterprise features such as transactional components, asynchronous activation, and object pooling. If you require any of these features in your .NET enterprise applications, you need to use COM rather than .NET role-based security .. The COM role-based security system and the .NET framework role-based security do not interoperate Therefore, you must decide early in the design which components will reside in COM and which will be .NET types; it will be hard to change the authorization code later.For an example of how to target both the .NET role-based security system and the COM role-based security system, see "Unify the Role-based Security Models for Enterprise and Application Domains with .NET" in MSDN Magazine.

In Additional To Role-Based Security, COM HAS Built-in Capability To Flow The Windows User Context And Information About Previous Callers.

Note: Mixing COM and .NET role-based security in your components is not a safe practice Windows switches between managed and unmanaged code when executing managed COM components, which makes principal information unreliable..

For code samples of COM role-based security, see "How to Use System.EnterpriseServices COM Role-Based Security" in the Appendix. For more information about using COM within .NET-based applications, see "Understanding Enterprise Services (COM ) in .NET "in the msdn library.

Performing Authorization In a Business Logic Component

Authorization checks are often required in the components that contain the business logic. You can call these components directly from the code in the user interface tier by using .NET remoting or by using service interfaces that encapsulate the business components, such as XML Web services. The authorization logic that you create frequently blends in with and becomes part of your component business logic. For information about how to separate business logic and authorization logic, see "Separating Business Logic and Authorization Logic" later in this guide. For information about how to Create Your Authorization Checks, See "Creating Authorization Code with .NET Role-based security" later in this guide.

Performing Authorization in Entities

An entity is a representation of data that may also include some form of behavior. You can use numerous kinds of entity such as DataSets, XML strings, XML Document Object Models (XML DOMs), and custom entity classes in your application, depending on the . The application. The application.

Entities Frequently Travel Between Application Tiers, Including Complete Round Trips in Which The Data is Retrieved from The Data Source, Sent To The User Interface, And Returned To The Data Source for Updating.

You can create classes to represent enttive CHECKS. For example, only users belonging to certin roles can create and initialize an entity object.

However, in Most Cases, You Should Not Perform Application Authorization In Entity Because:

· Pure data implementations such as DataSets, XML strings, and XML DOMs provide no inbuilt way to perform application authorization checks. · Entities-including entities provided by a third party-can be highly mobile. You can not be sure that client applications will be able To Use the entity authorization features.

Performing Authorization In a Service Interface

Service interfaces are façades that expose internal business logic to the outside world. Service interfaces provide an entry point to a business process, and they give you the flexibility to change the method signature of the internal process without affecting the outside caller.

................... ..

In the expense claim example, a service interface allows one claims processing component to be accessible to nontrusted clients by using an XML Web service and for trusted clients by using either .NET remoting or Distributed COM (DCOM). Service interfaces may also be custom Message Queuing (msmq) listener.

For Sample Code That Demonstrates Authorization In An XML Web Service, See "How to Perform Authorization In AN XML Web Service" in the appendix.

Performing Authorization in a Service Agent

.

You can use service agents to control access to external services by authorizing attempts to call the services from within your business tier. Service agents act as a proxy to an external service to allow you to perform validations, authorization, data formatting, and other tasks when your code calls the external service. Using a service agent also allows you to change which external service is being called and its signature, without affecting your business logic. you can write code in authorization service agents to prevent unauthorized users from calling external services.Note This type of authorization is separate from authorization that occurs in the external service. If you maintain the external service, perform the authorization check within the callee anyway, to ensure that the system is secure.

In The Following Service Agent Code, A User Cannot Pass A Claimxml Message To The ApproveClaim XML Web Service Method If He or She Does Not Belong To The CanApproveClaims Role.

Public ClaimResponse ApproveClaim (String Claimxml)

{

IF (Thread.currentPrincipal.Isinrole ("CanApproveClaims")))

{

WebService.claim claimservice = new webservice.claim ();

Return Claimservice.ApproveClaim (Claimxml);

}

Else

Throw new securityException

"You are not authorized to approve clal.");

}

For More Information About Dealing with Exceptions In Authorization Code, See "Handling Authorization Errors" Later in this Guide.

If the external service requires a specific user identity for authorization, create code within the service agent to pass an acceptable IIdentity object. Doing so changes the identity flow out of the component. For more information about manipulating identity flow, see "Designing Identity Flow for Authorization "Earlier in this guide.performing authorization in the data tier

The data tier is the last line of defense against illegitimate requests from the user interface, business components, or attackers attempting to access the data directly. From an authorization perspective, the data tier ensures that only approved users can access and modify data regardless of how The Attempt to Access IT.

Create Access Checks in The Data Tier When You NEED TO Perform The Following Actions:

· Prevent Sensitive Data from Propagating Outside The Data Tier.

Prevent Unauthorized Modification Of Data or Insertion of New Data.

.

To Perform Authorization In The Data Tier, You Can Use Several Techniques and Objects, Depending On Your Security Requirements. You can Perform Authorization In The Following Data Tier Components:

· Data Access Logic Components-Data Access Logic Components are responsible for retrieving data from the database, saving data back to the database, and processing any logic required to achieve these data operations. All application data travels to and from the database through the Data Access Logic Components to the rest of the application.

· Stored Procedures-Stored procedures can perform authorization logic within the database and retrieve and update the data. · Database Security Features-Use security features built into SQL Server to secure database objects such as tables, columns, views, and stored procedures.

For More Information About Working with Data Access Logic Components and Entities, See "Designing Data Tier Components" in the msdn library.

The Following Questions Will Help You Choose your Authorization Strategy in the data tier:

· How Complex Is The Authorization Logic?

· Simple-Perform The Authorization Check In A Stored Procedure.

· Complex-Perform The Authorization Check in The Data Access Logic Components, and Call DiffERENT Stored Procedures.

How Complex Is The Stored Procedure?

· Simple-Perform the authorization check in the Data Access Logic Components and call different stored procedures if creating multiple stored procedures that perform similar actions does not make maintenance more difficult.

· Complex-Perform The Authorization CHECK IN A Stored Procedure Takes A Parameter That Supplies Information for the Authorization Check.

If CREANG MULTIPLE Stored Procedures MAINTENANCE DIFFFICULT, Pass A Value To The Stored Procedure To Minimize The Number of Stored Procedures.

· How Many Stored Procedures Involve Authorization CHECKS?

· A small percentage-Create multiple versions of stored procedures that involve authorization checks. Create naming standards that obviously link the stored procedures, such as for GetClaimsMGR and GetClaimsEMP. This approach can be detrimental to application design as your application grows bigger, so use it with caution. · A large percentage-Create individual stored procedures that retrieve different data depending on who the connected user is. Use service accounts that represent application roles to connect to the database, allowing the stored procedure to perform the authorization check. This approach reduces Maintenance by minimizing the number of stored procedures.

FOLLOW THEST PRACTICES WHEN CREANIZATION CODE IN The Data Tier:

· Connect to the database with few service accounts to maximize the performance benefit of connection pooling. Connection pooling allows applications to reuse connections when the connection information (such as the user details) matches an existing connection. Therefore, do not create connections as individual users .

For More Information, See "Managing Database Connections" In The ".NET DATA Access Architecture Guide" in the msdn library.

PROTECT DATABASE Objects with grant and deny permissions.

Denying direct access to the data tables blocks users who connect to the database by using applications such as query analyzers, which do not enforce business logic on data updates or queries. Limit access to stored procedures and views to only allowed user / service accounts.

· Always use stored procedures when using application authorization techniques that involve WHERE clauses. Doing so helps prevent the SQL injection attack, in which attackers append additional (usually malicious) SQL statements to legitimate WHERE clauses. For more information about SQL injection attacks, see " BUILDING Secure ASP.NET Applications "in the msdn library.performing Authorization in Data Access Logic Components

Data Access Logic Components Are The Last Components That Expose FunctionAns Such, You Can Use The The Ensure Only Authorized Users CAN Access Or Modify Data.

Perform Authorization In Data Access Logic Components When:

· Multiple Applications Use the Same Data Access Logic Components.

.

· You need to rest............

Examples of Using Role-Based Security Within Data Access Logic Components Include Filtering Data Before It Propagates To Other Application Tiers And Controlling Which Stored Procedures your code executes.

For more detailed information about how to perform Authorization Checks, see "Performing Authorization Checks" Later in this Guide.

Filtering Data in The Data Access Logic Components

To ensurely You Return Only Suitable Information To Other Application Tiers, SELECTILELY Remove Sensitive Data In your data access logic component code.

The Following Code Sample Removes The Confidentialnotes Column from The Data When Uses Do Not Belong To The Manager Role.

Public DataSet getClaimData ()

{

Dataset claimdata;

// Database Code to Retrieve Dataset // ... if (! Thread.currentprincipal.isinrole ("manager"))

Claimdata.Tables [0] .Columns.remove ["confidentialnotes"];

Return claimdata;

}

Retrieving the unused column from the database is a waste of resources, especially if multiple columns are unused. Instead use stored procedures to select only the necessary data to increase database engine performance.

Calling DiffERENT Stored Procedures from the data access logic component

You can create multiple stored procedures that return the correct data for only one role. Your Data Access Logic Component code then performs an authorization check to determine which stored procedure to use based on the user's roles.

For example, you can create a version of a stored procedure for Managers and another for Employees that differ only by the data retrieved. The Data Access Logic Component code checks the user's role membership and calls the correct stored procedure.

The following code shows how the Data Access Logic Component method chooses which stored procedure to call based on the user's role membership. This code uses a helper class to avoid showing a lot of ADO.NET code. The Microsoft Application Blocks for .NET provides the SQLHELPER CLASS:

Public Dataset getClaimData (int32 ID)

{

DataSet DScLaimdata;

IF (thread.currentprincipal.isinrole ("manager"))

DSCLAIMDATA = SQLHELPER.EXECUtedataset (conn_string,

CommandType.StoredProcedure, "getclaimsmgr",

New SqlParameter ("@ ID", ID));

Else if (Thread.currentPrincipal.isinRole ("Employee"))

DSCLAIMDATA = SQLHELPER.EXECUtedataset (conn_string,

CommandType.StoredProcedure, "getclaimsemp",

New SqlParameter ("@ ID", ID)); Return DScLaimdata;

}

Performing Authorization In The Stored Procedures

You can Perform Authorization With Using TWO Main Approaches:

· Passing a role flag-Perform the authorization check in the Data Access Logic Component and pass an authorization result flag to the stored procedure. Doing so allows the stored procedure to filter the data based on the authorization flag, as the following code shows.

· Create Proc GetClaimDetails

·

· @Claimid int,

@Isususermanager bit

·)

· AS

·

· If @isusermanager = 0

· SELECT CLAIMDATE,

· Claimamount,

· ClaimDescription

From Claims

· WHERE

· Claimid = @claimid

· Else

· SELECT CLAIMDATE,

· Claimamount,

· ClaimDescription,

Approvedflag,

Confidentialnotes

From Claims

· WHERE

· Claimid = @claimid

· Passing the user identity or other role information-The Data Access Logic Component passes the user identity to the stored procedure as a parameter. The stored procedure then uses the parameter to look up the user's role membership and to select the data, as the following Code Shows.

· Create Proc getClaimDetails ·

· @Claimid int,

@UserIdentity varchar (20)

·)

· AS

·

· IF not exists (SELECT Userid from Userroles

· Where userid = @UserIdentity and role = 'manager')

· SELECT CLAIMDATE,

· Claimamount,

· ClaimDescription

From Claims

· WHERE

· Claimid = @claimid

· Else

· SELECT CLAIMDATE,

· Claimamount,

· ClaimDescription,

Approvedflag,

Confidentialnotes

From Claims

· WHERE

· Claimid = @claimid

Performing Authorization in The Database

Use the database security features as the foundation for a secure solution. You can then design application authorization by using stored procedures on top of the database security features, as described earlier in this guide.

Perform Authorization Using Database Security Features TO:

· Control Access to Tables, Column, Views, Stored Procedures, AND Other Data Objects Using SQL Data Definition Language (DDL) Security Statements Such As Grant, Deny, And Revoke.

· Restrict access to sensitive data at the lowest possible level (only the data) SQL Server does not natively support row-level authorization;. However, you can simulate it by creating views and stored procedures, as described later in this topic · Tighten. Security As Much As Possible. Note That High Level of Security May Come At The Cost of Decreased Scalability.

Before You Can Perform Authorization In The Database, You Must Choose How Your Application Will Connect To The Database.

Using SQL Roles to Simplify Administration

An Important Consideration In Your Design of Your System Is To Simplify The Maintenance of SQL Server by Using SQL Server Roles. SQL Server Provides Several Types of Roles, Including:

User-Defined Database Roles-Roles Created by the sp_addrole stiled procedure unique to the database. You can the database. You can the add s_addrolemember storedure.

Application Roles-Roles Created for Applications NOT for Windows Users or Groups.

· Fixed Database Roles-Fixed Roles Linked to Common Database Functionality, Such As SQL Administrator and Database Creator; sysadmin; and dbcreator.

For More Information About SQL Server Security, Authorization Roles, See "Building Secure ASP.NET Applications" in The MSDN Library.

Consider linking your application roles to the SQL Server roles to make administration consistent for both your application and SQL Server. Connect to the database as a service account that maps directly to a SQL role to achieve this linkage. The following section describes this technique.

Connecting to the database

To control access to tables, columns, views, stored procedures, and other data objects, SQL Server must be able to identify the user that requires authorization, by using one of the following connection approaches: · Windows authentication-If SQL Server is set up To Use Windows Only Authentication, The Process That Establishes The Connection Must Be Executing Under The Context of the User. SQL Server Uses This Windows User Account for All Forms Of Authorization.

This Approach Provides The Strongest Form Of Connection Security Because Credentials Are Not Passed over the wire.

· SQL Server authentication (mixed security) -If SQL Server is set up to use SQL Server and Windows authentication, you can use Windows authentication or you can specify the user in the connection string, which requires a user name and a password.

Create Several Service Accounts That Represent Application Roles Regardless OF HOW You Connect To The Database. The Grant Permissions on each Service Account Based on The Role's Requirements.

For Example, Create Service Accounts Such AS USR_Manager and USR_Approver To Implement The Principle of Least Privilege, Which Allows Access To Only A Subset of the Application Functionality.

....................... ...CRIPLITAverabna, THE, THE.

For More Information About Managing Database Connections, See ".NET Data Access Architecture Guide" in the msdn library.

Controlling Access to Sensitive Column

You can control access to columns using GRANT, DENY, and REVOKE permissions at the column level by using either T-SQL statements or the SQL Server Enterprise Manager utility. Use this authorization technique sparingly because maintaining a long list of column permissions for a large database IS TOO TIME Consuming to Be Practical. Use Service Accounts When You Connect To The Database, To Maketenance Management Management Management To Sensitive Rows

SQL Server does not implicitly let you control access to individual rows. However, you can create this functionality by adding a security column to the data table. The security column can hold either an individual user name or the minimum role that is required to access the data (assuming roles have some form of hierarchy). The security column allows you to restrict access to individual rows, but this technique is ineffective if users can directly access the data tables.

You can then control access to individual rows by combining the security column feature of the data table in a view or stored procedure with the SUSER_SNAME function, which retrieves the connected user name-or, more likely, the service account name.

.

Create View SecureClaimsView

AS

Select Claimdate, Claimamount, Claimdescription

From claims

Where [user] = SUSER_SNAME ()

Note This approach requires that you use the individual user identity when you connect to the database so that the SUSER_SNAME function retrieves the correct information. In this case, your application can not take advantage of connection pooling.

Creating Authorization Code with .NET Role-Based Security

This section describes how to write code to perform authorization with .NET role-based security. Role-based security enables you to perform authorization for an entire category or set of users rather than performing authorization for particular users.

You Must Take The Following Into Account:

· Performing authorization checks-There are several programming techniques for performing authorization checks using .NET role-based security. You must decide which technique to use, depending on the requirements of your application.

· Separating Business Logic and Authorization Logic-It Is Important to Have A Strategy For Separating Your Business Logic and your Authorization Logic.

Handling Authorization Errors-You Must Decide How To Handle Authorization Failure Affects Not Only Your Component Code But Also Any Code That Calls Your Component.

· Performing authorization with multiple threads-If your application uses multithreading, you must decide how best to associate an IPrincipal object with each thread. There are several options, depending on how you want to handle role-based authorization in a multithreaded application.

· Extending The Default Implementation-There Certain Situations In Which It is Beneficial To Extend The Default IMPLEMENTATION PROVIDED BY CLASES AND INTERFACES IN The .NET Framework Class Library.

Performing Authorization Checks

The .NET Framework Provides Three Ways to Check WHETHER A Principal IS A Member of A Role:

Manual CHECKS

· Imperative Checks

· Declarative Checks

This topic describes each of these techniques and offers guidance on when to use one technique instead of the others. Each technique offers similar performance because all of the techniques use the IsInRole method of the principal for the executing thread. Likewise, all three techniques assume that the principal automatically or manually links to the Thread.CurrentPrincipal property, as described in Designing Authentication for Authorization earlier in this guide.However, some significant differences exist between the techniques for checking whether a principal is a member of a role for example.:

· Both The Manual and The Imperative Styles Allow Complex Checks Involving Variables, As Described Later. The Choice Between The Manual and Imperative Styles IS One of Personal Preference.

· The Declarative Style Is Appropriate When Your Check Involves SIMPLY COMPLEX logic.

Of The Three Styles, Checking Roles Manually Is The Most Common Approach.

Checking Roles Manually

You can Manually Check WHETHER A User Belongs to a role by Calling The ISINROLE Method on The iPrincipal Object. However, Isinrole Behaves Differently for GenericPrincipals and WindowsPrincipals.

Checking Roles for GenericPrincipals

................................ ...Claifd.

IF (Thread.currentPrincipal.Isinrole ("Claims Approver"))

Checking Roles for WindowsprIncipals

When You Check Roles Manually Using Windowsprincipals, There Are Two Different Ways To Repesent The Role Name:

· Strings-Use strings if you are checking custom Windows user groups that administrators created for you, such as / Claims Department or / Claims Department. For example, the following code checks whether the user belongs to a custom Windows User group named / claims department: • IF (thread.currentprincipal.isinrole (@ " / claims department"

·))

For local machine level groups, use the Environment.MachineName property. You do not have to change the code when you deploy this property to a different computer. The following code shows how to use the Environment.MachineName property.

IF (thread.currentprincipal.isinrole

Environment.machinename @ "/ claims department")))

Note You must specify the word BUILTIN (as in BUILTIN / ) when using a string value to check for a built-in local Windows user group, such as Administrators or Users, to indicate that this is a special user group name.

Use the Whoami.exe tool to discover the correct syntax of the user's Windows user groups. The Whoami.exe tool is available at http://www.microsoft.com/windows2000/techinfo/reskit/tools/existing/whoami-o. . - SPECUTE The Tool.

Note .NET ROLE-BASED Security Does Not Support The Windows 2000 Format Username@domain.com.

· WindowsBuiltInRole enumeration-Use the WindowsBuiltInRole enumeration to check role membership against built-in Windows user groups such as Administrators or Users. For example, the following code checks whether the user belongs to the built-in Windows Users role.

· Windowsprincipal WP = (WindowsPrincipal) Thread.currentPrincipal;

· IF (WP.Isinrole (WindowsBuiltinrole.user))

.............. ..

Implementing Complex Manual Checks

Whether you use a GenericPrincipal or a WindowsPrincipal, you can implement complex access checks with multipart IF statements using logical operators such as logical AND (&&) and logical OR (||) in C # The following code shows such a check.:

IF (("Claims Approver" && (Amount

<100)) ||

(Thread.currentPrincipal.isinrole ("Senior Management" && (Amount

<500))))))

You can Perform Complex CHECKS BY Combining Operators Such as The Leater Than Symbol (>).

Handle Authorization Failure By Throwing An Exception. For More Information On Propagating Authorization Check Failures, See "Throwing Authorization Exceptions" Later in this guide.

Checking Roles Imperatively

You can use imperative checks to mandate that a user belongs to a particular role. You can imperatively check the user's role membership by creating a PrincipalPermission object and specifying the required role. The Demand method then performs the access check. If the principal is not a Member of the demanded role, The Common Language Runtime Generats A SecurityException.

.

PrincipalPermission Ceopermission = New

PrincipalPermission (NULL, "CEO");

CEOPERMISSION.DEMAND ();

Note In all the examples shown in this topic, you pass a null to the PrincipalPermission constructor for the User attribute so that any user who belongs to the appropriate role passes the access check. If you specify a user name, the runtime checks for a particular User, IT Defeats the purpose of using roles in this situation.you can check role membership imperatively by using the folload techniques:

· Implementing an OR scenario-You can implement complex checking by using the Union method, which represents an OR scenario. The following code checks whether the user is a member of the CEO or the Senior Manager role.

· PrincipalPermission Ceopermission = New

· PrincipalPermission (NULL, "CEO");

· PrincipalPermission mgtPermission = new PrincipalPermission (NULL,

· "Senior Manager");

CeOpermission.union (mgtpermission)). Demand ();

.

· PrincipalPermission Ceopermission = New

· PrincipalPermission (NULL, "CEO");

· PrincipalPermission mgtPermission = new PrincipalPermission (NULL,

· "Senior Manager");

· CEOPERMISSION.DEMAND ();

· Mgtpermission.demand ();

· Working with variables-You can check role names dynamically by combining variables, domain names, and machine names. This is similar to the way you perform manual checking, described earlier in this topic. The following code checks whether the user is a member of THE CLAIMS Department Role; The Environment.userdomainName Property Gets The Network Domain name associated with the capital user .. PrincipalPermission ClaimsPermission = New PrincipalPermission (NULL,

· Environment.UserDomainName @ "/ claims department");

· Claimspermission.Demand ();

Note The PrincipalPermission class also has an Intersect method, but this method does not serve any purpose for role checking because two users never intersect. This method exists because it is required to implement the IPermission interface.

You can handle the exception generated by failed calls to Demand by using standard exception handling techniques. For more information about propagating authorization check failures, see "Handling Authorization Errors" in this section.

Checking Roles Declaratively

You can place the PrincipalPermissionAttribute on classes, methods, and properties to declaratively require role permissions, as the following code shows. Note that member-level attributes override any class-level attributes.

[PrincipalPermission (SecurityAction.Demand, role = "CEO"),

PrincipalPermission (SecurityAction.Demand, Role = "Senior Manager")]]]

Public Class Claim

{

Public void viewclaims ()

{

// Only 'CEO' AND 'SENIOR Manager' Members CAN Access this

//Method

}

[PrincipalPermission (SecurityAction.Demand, Role = "ClaimsApprover")]

Public void approveClaIMS ()

{

// Only 'Claims Approver' Members Can Access this Method

}

}

The .NET compilers store the PrincipalPermissionAttribute as XML in the assembly metadata during compilation. During application execution, the runtime instantiates a PrincipalPermission object and performs the access check. For this reason, the capabilities of the imperative and declarative access checks are similar.

The runtime does not create proxies for the call and does not marshal any parameters until the authorization check passes; therefore, performance improves in cases in which the authorization check fails If the check fails, the runtime automatically throws a System.Security.SecurityException,. And no part of the protected method code can Execute. Because No Part of The Method Executes, You Cannot Perform More Complex Authorization Checks based on Business Logic, Such As Comparing Parameter Values.

The runtime evaluates the attributes at compile time, so you must hard-code the roles within the metadata;. Therefore, you can not implement a dynamic solution by using values ​​such as Environment.MachineName You also can not use the WindowsBuiltInRole enumeration because declarative checks use the Base Implementation of iPrincipal.

If you specify more than one PrincipalPermissionAttribute, the attributes are combined to represent an OR scenario. Therefore, the authorization check succeeds if the principal is a member of any of the roles. The following code demands that the caller of this method belongs to either the CEO or The Senior Manager Role:

[PrincipalPermission (SecurityAction.Demand, role = "CEO"),

PrincipalPermission (SecurityAction.Demand, Role = "Senior Manager")] public void viewclaimhistory () {}

Note It is not Possible to Declarative CHECK WHETER TO DETEER IS A MEMBER OF All of a list of roles.

The declarative technique tends to separate the authorization code from the other business logic. Separating the business logic from your authorization requirements improves the maintainability of your code. This separation allows you to change your authorization logic without changing your business logic, thereby reducing the possibility of INADVERTENTLY Introducing Business Logic Errors in The Code.

Separating Business Logic and Authorization Logic

The designers of the .NET role-based security framework created simple definitions for the IIdentity and IPrincipal interfaces, with the intent that developers would extend them to meet their needs You might want to extend this functionality when.:

· You NEED TO Store Some Extra Information About The User (More Than Simply The User Name and Roles) That The Application Requires.

For Example, You May Need to store information such as an organization of the user is located at a particular site.

You want to use your owmb role of role-based security information.

The .NET Framework provides an implementation (using the WindowsIdentity and WindowsPrincipal classes) that retrieves the role information from Windows. You will often want to implement custom extensions if you are maintaining your own store of information.

· You have specialized requirements for authorization. For example, you may need to write code that is dependent upon its deployment location. This is an example of "external knowledge" required to implement an authorization check.Handling Authorization Errors

If an authorization check fails within a business process, the component code needs to inform the caller of the failure. The best approach for doing so is to throw an exception. If you are implementing an asynchronous solution, treat the exception the same way as you .

When you design your components, assume that appropriate authorization checking has occurred at the trust boundary gatekeeper. If these assumptions are violated, your component should throw an exception. For example, you can assume that the user interface will never allow users not in the Administrator ............................

Throwing Authorization Exceptions

When Application Authorization Checks Fail, You Can Throw any of the following types of exception:

· System.ApplicationException-You can throw an ApplicationException with a message indicating that an application authorization check failed Use this exception type in your application if you consider authorization checks to be a subset of your business logic For example..:

· IF (! Thread.currentprincipal.isinrole ("Claims Approver"))

{

· Throw New System.ApplicationException ("User IS Not a Claims · Approver";

}

· System.Security.securityException-you can throw a securityException with a message indicating That An Application Authorization Check Failed. For example:

· IF (! Thread.currentprincipal.isinrole ("Claims Approver"))

{

· Throw new system.security.securityException

· "User is not a claims

AppRover ");

}

.

.

..................... ..

· Custom exceptions-As mentioned earlier, SecurityException is the default exception type when you use the declarative and imperative authorization styles. The runtime returns the standard message, Request for principal permission failed. You might need to add extra information to help the caller deal with the exception in a particular way, depending on the particular error. to address these needs, you can define your own custom exception classes to represent the different kinds of authorization errors that can occur in your application.

Creating your own custom exception classes benefits your application in the following ways: · The calling code can define separate catch handlers for each type of exception to handle errors in a particular way For example, the calling code can filter certain types of exception and log. Them for Operations Purposes.

· IF you design your authorization Exception Classes Correctly, You Can Reuse The in Multiple Applications That Involve Authorization Checks.

You Can Group Common Types of Authorization Failure Together. Doing So Allows Process And Components That AggRegate Others To Perform Corrective Action.

For More Information About Creating Your OWN Exceptions and for a Sample Implementation, See "How to create an authorization custom exception type" in the appendix.

Note Propagated authorization exceptions should not contain any sensitive information that could compromise the system. For more information about this and other exception management best practices, see "Exception Management in .NET" in the MSDN Library.

Handling Authorization Exceptions

The calling code can define catch handlers for authorization exceptions in addition to your role-based authorization exceptions. You might receive several forms of SecurityException violations, depending on your deployment scenario. For example, if you launch your code from a semitrusted environment, the runtime might throw exceptions to indicate code access security permission failures, such as file access issues. Although these exceptions are not related to role-based authorization, they might result in a SecurityException.

You can write exception-handling code to differentiate between role-based authorization exceptions and other types of authorization exceptions. Use the PermissionType property of the SecurityException object to check whether the exception relates to role-based authorization, as the following code shows.try

{

// Code Here That Could Create a role-based Authorization Exception,

// Such as an imperative check.

}

Catch (SecurityException SE)

{

IF (se.PermissionType == TypeOf (PrincipalPermission))

// Do Something Here if Exception Is Role Related.

Else

// Do Something Here if Exception is not role related.

}

The result of the PermissionType property allows you to filter both code access security and role-based authorization exceptions. After you filter an exception, you can throw a custom exception or handle the exception internally in the callee.

Performing Authorization with Multiple Threads

Most .NET-based applications use multiple threads to improve responsiveness or to perform work asynchronously. Multithreading introduces complexities when you work with principals because each thread must link to an IPrincipal object. The runtime copies the IPrincipal object to any new threads that the parent thread Creates.

The Thread.currentPrincipal Property Returns A Different IPRINCIPAL OBJECT According to the Following Rules:

· If you expectirate associate an iprincipal object with the thread, That iPrincipal Object is returned.

· If you do not explicitly associate an iprincipal object with the thread and you use the setthreadprincipal method, a Default iPrincipal Object for the application domain is returned.

Calling the AppDomain.CurrentDomain.SetThreadPrincipal method ensures that the runtime uses a specific IPrincipal object for current and new threads. This option is not recommended for ASP.NET because the runtime handles principals. Also, it can affect other threads that are running on behalf Other users.note the runtime throws a policyException if you call this method More Tan once during the lifetime of an application domain.

· If no IPrincipal object or default application domain IPrincipal object is associated with the thread, an IPrincipal object of the type specified in the SetPrincipalPolicy method is returned, as described earlier in this guide.

· If you do not use any of the preceding methods, null (or Nothing) is returned.

Extending The Default IMPLEmentation

FOLLOW THESE Guidelines when Extending The .Net-Based Application Authorization Framework:

· Implement the IIdentity and IPrincipal interfaces-This will ensure that your extensions are compatible with other features that use the .NET role-based security model, such as the ASP.NET URL authorization feature.

· Use lazy initialization where possible-If the task of populating the role information to construct your IPrincipal object is time consuming, you should delay this activity until the first time the information is required.

· Attach your IPrincipal object to the executing thread-This allows you to use the declarative, imperative, and manual authorization checking styles mentioned previously. It also works well with other technologies, such as ASP.NET authorization.

Deciding on an extension statate

Decide what type of extension to create and where you should create it Table 1 contains some common extensions and indicates where you should create the additional logic required.Table 1:. Where to create your application authorization extensions

TYPE OF EXTENSION

Custom Identity

Custom Principal

Helper Class

User-Specific Information

X

Permission Or Role Related

X

External Knowledge Required

X

Implementing Custom Identities

You Should Create Your Own Class That Implements IIDENTITY WHEN You Require More Functionality Than Is Provided by The GenericIdentity Or WindowsIdentity Object. Possible Enhancements INCLUDE:

· Managing tokens or user identifiers. This approach is generally required when you need to encapsulate an authentication process that involves tokens. The WindowsIdentity, FormsIdentity, and PassportIdentity classes manage a token that represents the user. The classes use a Microsoft Win32® token, forms Authentication Ticket, And The Passport Unique Identifier (PUID), Respective.

For Example, You Could Create Your Own Custom Identity When Using An Isapi Single Sign-on Solution.

· Encapsulating your own code in the IIdentity object, which is then available to all the applications. For example, the PassportIdentity provides many extra properties and methods over the standard IIdentity interface, including profile information. This extra information can be added to your identity class . using standard techniques such as public properties Another example might be that you frequently base authorization checks on the user's manager; in this situation, you can provide the user's manager as a value on the identity.

Implementing Custom Principals

You should create your own class that implements IPrincipal when you require more functionality than is provided by the GenericPrincipal or WindowsPrincipal object Possible enhancements include:. · Implementing your own enumeration of roles in the same way that the WindowsBuiltInRole enumeration works for a WindowsPrincipal This can. Be achieved by overloading the isinrole method to enable call code to cho together ie string.

Checking WHETER THE PRINCIPAL BELONGS TO Any Role in A Specified List. For example:

CustomPrincipal.InAnyrole (String [] Roles);

· Accessing the list or enumerating The Roles That The Principal Belongs To. For example:

· String [] Roles = CustomPrincipal.Roles;

· Enforcing Some Type of Role Hierarchy So That Some Roles Are Considered "More Than" OR "Less Than" Other Roles. For Example, A "Senior Manager" is "more" or Above a "Junior Manager."

Reusing Authorization Implementations

You can reuse your application authorization framework across multiple applications if you design the framework with reuse in mind. Reuse typically involves the code and infrastructure used to implement the authorization capabilities.

Benefits of Reusing Your Application Authorization Framework Include The Following:

· Developers in your Organization Can Target One Application Authorization Framework.

· You Can Easily Reuse Components That Adhere To The Application Authorization Framework In Other Applications Because They A Standard Authorization Approach.

· The authorization subsystem becomes a focal point for synchronizing with other systems or platforms. Reuse alleviates the need to synchronize authorization details from legacy applications to new applications that need the authorization data. · Authorization management is consistent across applications and makes the experience consistent for administration And Operations Personnel.

This Section Includes Some Best Practices for Reusing Authorization IMPLEMENTATIONS.

Creating a Reusable Authorization Framework

You Can Choose How Much of Your Application Authorization Framework to Reuse Across Applications. Options include:

· Reusing One Authorization Database and One XML Web Service That Accesses The Authorization Data.

· Reusing The Authorization Framework But Having Separate Database Instances for Each Application.

Figure 6 shows an esample of how you can usually appliorthure reuse.

Figure 6. Logical Representation of Application Authorization REUSE

Note The Following Points in Figure 6:

· Different Applications CAN Reuse The Same Authorization Framework.

· An Authorization Service Provides Secured Access to Authorization Data.

· A Centralized Database Holds The Authorization Data.

· A Single Administration Utility Provides All Configuration.

A local cache improves Authorization Performance.

.

Table 2: How to Reuse Authorization Components

Component

Description

How to reuseauthorization framework

Custom Core Created To Support Authorization Capabilities, Such As Custom Principals, Identities, And Exceptions

Create an assembly cup all the customer, strongly name the assembly, strongly name. ..Opl.

Authorization cache

An Optional Unit of Functionality That Keeps The Authorization Information Physically Close To Where The Framework Works with IT

Create a Hashtable object (or other such in-memory store) with an appropriate method for refreshing on demand. For efficiency, IPrincipal objects should use this cache for retrieving role membership instead of going to the database.Use encryption if you need to protect or Hide The Cached Data; Otherwise, Sign The Cached Data To PREVENT TAMPORTANT OF You Store The Data In A Local File or in Another Vulnerable Location At Another Vulnerable Location At Another Vulnerable Location At Another VulneRable location

Authorization Service

An interface (or Gatekeeper) to the Authorization Data

Create an out-of-process component that runs under a security context that can access the authorization store. Using an out-of-process component allows you to authorize access to the store by checking to see whether the access occurs by the account specified. This allows you to prevent other users from accessing the store.Alternatively, you can build an XML Web service for central reuse. This provides the greatest interoperability. Remember to protect the communication channel between the authorization service and the authorization framework.

Administration Utility

A User Interface That Application Administrators Use to Maintain Authorization Data

Create a Central Web Site on Which Administrators Can Adjust The Authorization Settings.Alternative, Create a Reusable Graphical User Interface That You Deploy with Each Application.authorization Data

The Definition of The Authorization Data Schema, Stored Procedures and Data Access Logic Components

Use ONE DATABASE for All Authorization Data. Alternative, Use A Standard Authorization Schema for Each Application.

SECURING THE IMPLEMENTATION

To Secure Your Reusable Authorization Framework, Follow these Guidelines:

· Perform Authentication Checks on Callers to The Authorization Data Store. Doing So Prevents Unauthorized Parties from Querying The Authorization Information.

· Use a secure transport such as ssl or ipsec.

· Deploy An Authorization Service, AS AN XML Web Service, In A Separate Directory for Each Application. Doing So Allows You To Configure The Service To Work Only with the application in which you deploy it.

Improving the Performance of a Reusable Authorization Framework

Improve The Performance of Your Reusable Application Authorization Framework by USING THE FOLLOWING TECHNIQUES:

• Batch Authorization Queries WHENEVER POSSIBLE TO AVOID FREQUENT OUT-OF-Process Round Trips for Multiple Uses in a Single Request.

· Cache the authorization data close to where you will use it with an in-memory store, such as a Hashtable. The cache also reduces dependencies on the location and organization of the underlying store. You might also want a separate cache for each physical computer , for performance and increased security.

· Implement scheduled or on-demand refreshes of the cache information. Implement lazy initialization of the authorization cache to avoid retrieving authorization information information for the acity

Appendix

This appendix incrudes The Following Topics:

How to enable Authorization in a .NET Remoting Component

· How to Perform Authorization in An XML Web Service

· How to create an authorization custom Exception Type

· How to change the principal in an asp.net application

· How to build a genericprincipal using SQL Server

· How to use system.EnterpriseServices COM ROLE-BASED Security

How to enable Authorization in a .NET Remoting Component

.NET remoting does not automatically flow the principal from one application domain to another, except when the domains are in the same process. You must manually pass this information between the caller and the callee and ensure that the information remains secure during passage.

For Information About .NET Remoting with Windows Authentication, See ".NET Remoting Security Solution" in The Msdn Library.

................. ..

The Callcontext Class Lets You include Additional Information WHEN A Method Is Called on The Remote Object. This Information Can Be Anything You Require for the Individual Method, Such as User Information.

Only types that implement the ILogicalThreadAffinative interface are sent to a server that is in a separate application domain For example, you can create a simple type that implements ILogicalThreadAffinative;.. That stores an object based on IIdentity or IPrincipal This object would be accessible in the Remote Object, and you could check role membership.The Following Code Shows How To create a class thismeds the iligethreadaffinative interface and personists an iPrincipal based object.

Using system;

Using system.runtime.remoting.Messaging;

Using system.security.principal;

Namespace RemotingPrincipalFlow

{

///

/// The Storage Used to Transport The Principal Between Layers.

///

[Serializable]

Public Class PrincipalStorage: iLogicalthReadaff InnATIVE

{

Public PrincipalStorage (iPrIncipal Principal)

{

// Check the parameter.

IF (Principal == NULL)

Throw new argumentnullexception

"Principal", "The Argument Cannot Be Null.");

// set the internal principal.

_principal = principal;

} Iprincipal _principal;

Public IPRINCIPAL Principal Principal

{

get

{

Return_principal;

}

}

}

}

...........................

Using system;

Using system.threading;

Using system.runtime.remoting.Messaging;

Namespace RemotingPrincipalFlow

{

///

/// The Remote Class.

///

Public Class Remobject: MarshalByrefObject

{

Public remobject () {/ * Empty constructor * /}

Public void exampleMethoduSingCallContext ()

{

// Retrieve The Principal from the CallContext.

PrincipalStorage PPAL = CallContext.getdata ("Principal") AS PrincipalStorage;

// set the current principal.

IF (ppal! = null)

Thread.currentprincipal = ppal.principal;

// Show The Principal Information.

Console.writeline ("Identity.Name:"

Thread.currentprincipal.Identity.Name);

}

}

}

. ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

Using system;

Using system.runtime.remoting;

Using system.runtime.remoting.channels;

Using system.runtime.remoting.channels.tcp;

Using system.runtime.remoting.Messaging;

Using system.security.principal;

Using system.threading;

Using RemotingprincipalFlow;

Namespace RemotingPrincipalFlow

{

///

/// The client application.

///

Class RemotingPrincipalFlowDemoClient

{

[Stathread]

Static void main (string [] args)

{

// Register Remoting Client Channel.

ChannelServices.RegisterChannel (New Tcpchannel ());

// register the remoted class.

RemotingConfiguration.registerWellknownClientType

TypeOf (Remobject),

"TCP: // localhost: 6000 / transobject");

// set the current principal.

Thread.currentprincipal = new genericprincipal

New GenericIdentity ("Doug", "User"),

New string [] {"admin", "user"});

// Use the callcontext to set the current print.

CallContext.SetData ("Principal",

NEW PrincipalStorage (thread.currentprincipal);

Console.writeline ("Calling Remote Object ...");

// Use the remoted object.

Remobject RO = new remobject ();

Ro.exampleMethodusingCallContext ();

Console.writeline ("Call Complete, Press Any Key ..."); console.readline ();

}

}

}

The Following Code Shows The Server Application That Registers The Remote Object.

Using system;

Using system.runtime.remoting;

Using system.runtime.remoting.channels;

Using system.runtime.remoting.channels.tcp;

Namespace RemotingPrincipalFlow

{

///

/// The Server Host Application.

///

Class RemotingPrincipalFlowDemoServer

{

[Stathread]

Static void main (string [] args)

{

// register the remoted class.

RemotingConfiguration.registerWellkNownServiceType

Typeof (Remobject), "Remobject",

WellknownObjectMode.singleton;

// Register Remoting Server Channel.

ChannelServices.RegisterChannel (New Tcpchannel (6000));

Console.writeline ("Running Server, Press Enter to Quit";

Console.readline ();

}

}

}

How to Perform Authorization In an XML Web Service

In the following code, the ProcessClaim XML Web service method performs an authorization check and throws an exception if the check fails. The check determines whether the sender of the expense claim is authorized to send it.

Using system;

Using system.xml.serialization;

Using system.Web.services;

Using system.security.permissions;

Using system.security;

Namespace Authzinws

{

///

/// summary description for class1.

///

[XMLinClude (TypeOf (EmployeecLaim)]]

[XMLINCLUDE (TypeOf (ContractorcLaim)]]

Public Class Claim

{

// Base Class Code for All Claims.

Public void processclaim ()

{

}

}

Public Class EmployeecLaim: Claim

{

New public void processclaim ()

{

}

}

Public Class ContractorcLaim: Claim

{

New public void processclaim ()

{

}

}

Public class claimsserviceInterface {

[WebMethod]

[PrincipalPermission (SecurityAction.Demand, Authenticated = true)]

Public Void ProcesscLaim (Claim Claimin)

{

Try

{

PrincipalPermission ClaimtypePrincipalPerm = NULL;

Claimin Is EmployeecLaim

ClaimtypePrincipalPerm =

New PrincipalPermission (NULL,

"EMPLOYEE");

Else IF (Claimin Is Contractorclaim)

ClaimtypePrincipalPerm =

New PrincipalPermission (NULL,

"Contractor");

Else

Throw New ApplicationException

"Claim Type is not allowed.");

ClaimtypePrincipalPerm.Demand ();

Claimin.ProcesscLaim ();

}

Catch

{

Throw New SecurityException ("Authorization Failed");

}

}

}

}

To ensure that you are dealing with an authenticated callee, specify the Authenticated property of the PrincipalPermissionAttribute. Doing so also ensures that the Thread.CurrentPrincipal automatically provides the correct IPrincipal object for the imperative authorization check.

.

Static void main (string [] args)

{

Localhost.claim claimsubmission = new localhost.employeeclaim ();

Localhost.claimsserviceInterface ClaimsService =

New localhost.claimsserviceInterface ();

Claimsservice.ProcessClaim (Claimsubmission);

}

This code assumes that the authenticated user belongs to application-defined roles of either Employee or Contractor. For information about how to load the IPrincipal object with roles, see "How to Change the Principal in an ASP.NET Application and How to Build a GenericPrincipal USING SQL Server "Later in the appendix.

How to create an authorization prefeom exception Type

For troubleshooting or auditing, you might throw a custom exception that contains more information than does a typical authorization failure-for example, the user name or e-mail address of the person who caused the exception. The following code creates an exception class for handling An Authorization Failure. The Exception Class Includes the user name from thread.currentprincipal.Identity.USING SYSTEM

Using system.io;

Using system.security;

Using system.security.permissions;

Using system.threading;

Using system.security.principal;

Namespace Authzexceptions

{

Public Class ApplicationAuthorizationException: ApplicationException

{

// Default constructor.

Public ApplicationAuthorizationException ()

{

Setusername ();

}

// The Constructor Accepts a Single String Message.

Public ApplicationAuthorizationException (String Message):

Base (Message)

{

Setusername ();

}

// The constructor accepts a string message and an inner exception,

// Which is wrapped by this customer. Exception Class.

Public ApplicationAuthorizationException

String Message, Exception Inner: Base (Message, Inner)

{

Setusername ();

}

// Why not add the whole principal?

// the systemException class is Serializable, So you want to add

// Only Information That Can Be Serialized.

// Identity Objects Offen Encapsulate a token (Windows) That Cannot

// be serialized, so use the string value of the identity instead.

//

// other items you might want to add incn:

// Authentication Type

// Type of Principal

Private void setusername ()

{

IF (Thread.currentPrincipal! = NULL)

m_strusername =

Thread.currentprincipal.Identity.Name;

}

Private string m_strusername;

Public String Username

{

Get {return m_strusername;}

}

}

The following code calls a component that performs the authorization check. When the check fails, the catch block or blocks test the exception and display the user name from the ApplicationAuthorizationException.

Using system;

Using system.security;

Namespace Authzexceptions

{

Class Callerclass

{

///

/// The main entry point for the caller application.

///

///

[Stathread]

Static void main (string [] args)

{

Try

{

Calleeclass.PerformAction ();

}

Catch (ApplicationAuthorizationException EX)

{

Console.writeLine (se.Message "" ex.username);

}

Catch (SecurityException EX)

{

Console.writeLine (ex.Message);

}

Finally

{

Console.readline ();

}

}

}

}

The following code acts as the callee component that performs the authorization check. This code deliberately denies access to a particular file so that an exception not related to authorization can occur. The catch block uses the PermissionType property to filter the two possible exceptions.

Using system;

Using system.security;

Using system.security.permissions;

Using system.security.principal;

Namespace Authzexceptions

{

// the fileiopermission is buy @ly to demonstrate a

// securityException in the readfile method.

[Fileiopermission (securityAction.deny, read = @ "c: /file.txt")]]

Class Calleeclass

{

///

/// The class representing the callee.

///

///

// Method That Performs Authorization Check.

[PrincipalPermission (SecurityAction.Demand, role = "CEO")]]

Static void authorize ()

{

Console.writeline ("Authorization Succeeded");

}

Public static void performaction ()

{

// link the WindowsprIncipal

Appdomain.currentDomain.setPrincipalPolicy (PrincipalPolicy.WindowsPrincipal);

Try

{

// Perform The Authorization Check.

Authorize ();

// Perform action That Creates a securityException.

Readfile ();

}

Catch (SecurityException SE)

{

IF (se.PermissionType == TypeOf (PrincipalPermission))

Throw New ApplicationAuthorizationException

("Authorization Failed", SE);

Else

Throw se;

}

}

// Dummy Method to throw a securityException.

[Fileiopermission (securityAction.demand, read = @ "c: /file.txt")]]

Static void readfile () {}

}

}

How to change the principal in an ASP.NET Application

You can change the default IPrincipal object within an ASP.NET application to include application-specific roles loaded from a data store after authentication takes place. Changing the IPrincipal object lets you rely on any type of authentication while still using application-defined roles for your authorization checks. The Application_AuthenticateRequest event handler is the best location to change the IPrincipal object because the authenticated identity is available and the event handler executes before any Web page or XML Web service logic.

The following code replaces the HttpContext.Current's IPrincipal object with a GenericPrincipal object based on the authenticated identity and adds the object to the HttpContext.Cache to improve performance:

Protected Void Application_AuthenticateRequest (Object Sender, Eventargs E)

{

// Check WHETHER THERE IS A CURRENT User and That

// Authentication Has Occurred.

IF (! (httpcontext.current.user == null))

{

Iidentity CurrentUserIdentity = httpContext.current.user.Identity;

// Check to see WHETHER The Principal Was Cached.

String cachedprincipalkey = "cachedprincipal" id.name; if (httpContext.current.cache [cachedprincipalkey] == null)

{

// load the principal by calling the getprincipal method.

HttpContext.current.cache.add (

CachedPrincipalKey,

GetPrincipal (CurrentUserIndentity),

NULL,

Datetime.maxvalue,

New TimeSpan (0, 30, 0),

CacheItemPriority.Normal,

NULL);

}

HttpContext.current.user = (iPrincipal)

HttpContext.current.cache [CachedPrincipalKey];

}

}

The sample uses the cache to reduce the number of queries to the database. The cache was selected for the example because the cache lets you set a timeout value. However, using session state will require less testing, because ASP.NET guarantees that the user has access to only his or her session. Care needs to be taken with this sort of code to ensure that the thread running the user's request can never be issued with the wrong Principal. For a sample implementation of the getPrincipal method, see the next topic .

How to build a genericprincipal using sql server

The Following Example Presents A Simple Database Schema That You Can Use to Populate A GenericPrincipal with Roles. Run The Following Code To Create The Userroles Table:

If EXISTS (Select * from dbo.sysObjects where id =

Object_id (n '[userroles]') And ObjectProperty (id, n'susertable ') = 1)

Drop Table [userroles]

Go

Create Table [Userroles]

[Username] [varchar] (50) Collate SQL_LATIN1_GENER_CP1_CI_AS NULL,

[Role] [varchar] (50) Collate SQL_LATIN1_GENER_CP1_CI_AS NULL

) On [primary]

Go

INSERT INTO [CLAIMS]. [DBO]. [Userroles] ([username], [role])

Values ​​('chris',' admin ")

INSERT INTO [CLAIMS]. [DBO]. [Userroles] ([username], [role])

VALUES ('Doug', 'Admin') Insert Into [Claims]. [DBO]. [UserRoles] ([UserName], [Role])

VALUES ('Doug', 'Manager')

Go

The GetPrincipal method that follows takes an IIdentity as a parameter, which then provides the identity information to the GenericPrincipal. The code uses the name of the identity to look up the roles in the UserRoles table for populating the roles in the IPrincipal object.

Notice that the code passes the identity name as a string to the GenericIdentity constructor rather than using the IIdentity parameter. Passing the identity name as a string allows you to use the code in conjunction with any authentication type.

.

Private IPrincipal GetPrincipal (iIdentity User)

{

// Get The Roles from The Table Based ON A User Name ONLY.

String SQL =

"Select Role from Userroles Where UserName = '" User.Name "'";

SqlConnection MyConnection = New SqlConnection

"Data Source = localhost; Initial Catalog = Claims; Integrated

Security = SSPI ");

Sqlcommand mycommand = new sqlcommand (sql, myconnection);

MyConnection.open ();

SqldataReader myDataReader = mycommand.executeReader ();

Arraylist alroles = new arraylist ();

// load the roles Into an arraylist.

While (MyDataReader.Read ())

Alroles.add (MyDataReader.getstring (0));

MyDataReader.Close ();

Mycommand.dispose ();

MyConnection.Close ();

MyConnection.dispose ();

// Convert the Roles to a string [], and load genericprincipal.

String [] myroles = (String []) Al.toArray (TypeOf (String));

Return New GenericPrincipal (

New genericIdentity (user.name, user.gettype ());

}

For Sample Code That Calls The GetPrincipal Method, See "How to Change The Principal in An ASP.NET Application" Earlier in this appendix.

How to use system.EnterpriseServices COM ROLE-BASED Security

.

To Perform A Manual OR A Declarative Access Check

.

Use the accesschecksleveloption.applicationunications at the application and component level.

2. Enable Access Checks for Each Component That Requires Role-based Security by Applying The ComponentAccessControlttribute to the appropriate class.

3. Derive from servicedcomponent for any class requiring role-based checks.

4. Add ann offerge the assembly, clas, interface, or method.

Note Stes 1, 3, And 4 Don't Actually Have to Be Done In Code. The Component Services Management Console.

To Complete Configuration of the Component Services Application

1. Configure Authentication to at Least The Call Level; OtherWise, The Interceptor Cannot Access Caller Information.

2. Assign Users to Appropriate Roles.

Note To make your application work, you might need to add steps, such as installing the assembly in the global assembly cache. These steps are specific to your deployment and are not covered in this guide. For more information about installing a Component Services application, See "COM Integration: How .NET Enterprise Services CAN Help You Build Distributed Applications" in msdn magazine.performing manual COM ROLE CHECKS

Manual role-based checks rely on the availability of the security call context object within your application code. This context object is available if you enable security for your component services application.

When Checking COM ROLE Membership Manually, Use The Following Techniques:

· Check whether a user belongs to a particular role by calling the IsCallerInRole method on the SecurityCallContext object. As a precaution, check whether security is enabled before you check role membership. The result from calling IsCallerInRole is always true if security is disabled.

The Following Code Shows How To Test Security and Check for Role Membership.

IF (ContextUtil.Isecurityenable)

Return SecurityCallContext.currentCall.iscallerinrole

"CLAIMS Approver");

· Create Complex CHECKS BY Using Multipart IF Statements Using Standard Syntax Such As Logical and (&&) And Logical OR (||) Checks. The Following Code Shows Such A Test.

IF (SecurityCallcontext.currentCall.iscallerinrole ("Claims

AppRover ") ||

· SecurityCallContext.currentcall.iscallerinrole ("Senior

· Management "))

· Create constants in your application, or retrieve the user roles from an external source, such as a database. · Use the SecurityCallContext.CurrentCall.OriginalCaller property to access information about the user. This property returns a SecurityIdentity object, as the following code shows .

· Debug.writeline (SecurityCallcontext.currentCall.originalcaller.accou

· Ntname);

Performing Declarative COM ROLE Checks

Declarative checks enable users who belong to a specified role to activate the component and call any of its public methods. This type of role check is analogous to specifying the declarative .NET role-based security attributes at the class level. You specify the role that .

Using system;

Using system.enterprises;

Using system.reflection;

[Assembly: ApplicationName ("expenses")]

[assmbly: ApplicationActivation (ActivationOption.server)]

[Assembly: ApplicationAccessControl (True,

AccessChecksLevel = AccessCheckSlevelOption.ApplicationComponent]

[Assembly: SecurityRole ("Claims Approver")]]]

[Assembly: SecurityRole ("Senior Management")]]]

Namespace Expenses

{

[ComponentAccessControl ()]

[SecurityRole ("Claims Approver")]]]

Public Class Claim: ServicesDComponent

{

Public Bool Approve () {Return True;}

}

}

Performing Declarative Checks Down To The Method Level

Performing Declarative Checks On Methods Requires More Stes Than Do Checks At The Class Level:

IMPLEMENT AN Interface.

2. Include the SecureMethodAttribute at the class or the method level. This attribute configures role security at the method level when you install the application into COM . To allow all methods to be secured either declaratively within the code or manually using the administration utility, specify To Link The Methods To Roles, Use The SecurityRoleattribute on The Method Implementation.

4. Add users manually in the Component Services management console to the Marshaler role. COM creates this role automatically when you install the application into COM so that both managed and unmanaged clients can call the secure methods.

The Following Code Demonstrates these Steps.

Using system;

Using system.enterprises;

Using system.reflection;

[Assembly: ApplicationName ("expenses")]

[assmbly: ApplicationActivation (ActivationOption.server)]

[Assembly: ApplicationAccessControl (True,

AccessChecksLevel = AccessCheckSlevelOption.ApplicationComponent]

[Assembly: SecurityRole ("Claims Approver")]]]

[Assembly: SecurityRole ("Senior Management")]]]

Namespace Expenses

{

Public Interface Iclaim

{

Bool approve ();

}

[ComponentAccessControl ()]

[SecureMethod]

Public Class Claim: ServicedComponent, Iclaim

{

[SecurityRole ("Claims Approver")]]]

Public bool approve () {}

}

}

Feedback and support

· Questions? Comments? Suggestions? For feedback on designing appliment-management authorization, please e-mail us at devfdbck@microsoft.com.

· The Application Blocks for .NET components and guides are designed to jumpstart development of .NET distributed applications. The sample code and guidance is provided "as-is." Support is available through Microsoft Product Support for a fee. · A newsgroup has also BEEN CREATED TO Assist You with the application blocks for .NET Components and guides. Use this newsgroup to consult with your counterparts, peers, and Microsoft Support Professionals in an Online, Open Forum.

· Everyone else benefits from your questions and comments, and our development team is monitoring the newsgroup on a daily basis: Newsgroup: Web-Based Readerhttp:? //Msdn.microsoft.com/newsgroups/loadframes.asp icp = msdn & slcid = us & newsgroup = Microsoft.public.dotNet.Distributed_APPS

· Newsgroup: nntp readynews: //msnews.microsoft.com/Microsoft.public.dot.com.distribute_apps

转载请注明原文地址:https://www.9cbs.com/read-119860.html

New Post(0)