Design authorization of application management

xiaoxiao2021-03-06  71

Summary

This guide introduces a single-layer or multi-layer application based on Microsoft® .NET, the authorization guiding principle, which is authorized by application management, mainly discusses common license tasks and programs, and provides the appropriate information to help you choose the best way. And technology. This guide is suitable for architectural designers and developers.

This guide assumes that the reader has learned about the basic knowledge of the topics such as Windows Authentication and Authorization, XML Web Service, and .NET Remoting. For more information on design distribution .NET applications, see "Designing Applications and Services" in MSDN® Library. For more information on distributed application security design, see Building Secure ASP.NET Applications in MSDN Library. For other conventional design guidelines, see the .NET Architecture Center in Microsoft TechNET.

download

Click here to download this guide (PDF format).

table of Contents

This guide includes the following sections:

Introduction to authorize the authorized authentication design for Authorized identification streams Executive Authorization in Enterprise Applications Authorization-based .NET Security Settings Creating Authorized Codes Repeat Authorization Implementation Appendix

Introduction

This guide describes how to implement authorization, interpret the terms "authorization" in an .NET-based application and discuss several mechanisms of performing authorization. This guide also includes the following:

Identification and main body and other important concepts. How to use role-based security settings to authorize a class of users with the same security privilege. The main difference between the role based .NET and COM security settings.

What kind of authorization mechanism usually depends on the method of verifying user identity (identification). This guide will explore the following:

Difference between Windows Authentication and Non-Windows Authentication. How these authentication mechanisms affect authorization. How to deliver identification information for authorization to the remote application layer.

In a typical enterprise application, you need to perform different types of authorization at different levels of the application. To help you identify authorization needs of each layer, this guide describes the typical license tasks commonly used in user interface layers, business and data layers in different scenarios, business and data layers. Figure 1 shows some important authorization issues that appear on each layer of the enterprise application.

Figure 1: Executive authorization in the layers of the enterprise application

The .NET Framework class library provides a variety of interfaces and classes to help you perform licenses with roles .NET security settings. This guide introduces:

Several techniques for checking if the user belongs to a particular role. How to deal with an authorization error. Special authorization issues that appear in multi-threaded .NET applications.

Most of the work done when defining the license framework can be reused in multiple applications. This guide will summarize the following:

How to define a reusable license framework. Make the security and performance of the frame to the best principles.

Note: This guide is applied to the authorization of application management using the .NET Framework function. The Authorization Manager API and Microsoft Management Console (MMC) management units in the Microsoft Windows® Server 2003 Series operating system provide the application with a complete role-based access control framework. Authorization Manager API is also known as Azman, which provides a simplified development model for managing flexible packets and business rules and can be used to store authorization policies. For more information, see MSDN LIBRARY

Authorization Interfaces (English) and

Authorization Objects.

Learn about authorization

"Authorization" is an acknowledgment of whether or not to perform an authority of an operation by verifying the subject (user, computer, network device, or assembly). Protection provided by authorization only allows the specified user to perform specific operations and prevent malicious behavior. The content of this section is as follows:

Protection provided by authorization. Basic authorization. The authorization function of .NET Framework.

Reduce security threat

Only authorized is not enough to ensure the security of the application, so this guide will briefly introduce several threats facing applications. Here are some common security threats, these threats are usually abbreviated as "stride", including:

Identify fraud - unauthorized user pretending application legitimate users to tamper data - attacker illegally changed or destroy data Debation - user denial executing ability information leakage - sensitive data is leaked to the person who should be accessible or Location Reject Service - Leading the user unable to use the application's damage behavior privilege upgrade - users illegally obtain excessive application access privileges

You can use the following techniques to resolve the Stride threat:

Authentication - strict authentication helps to reduce identification deception. When the user logs in to Windows or launch the application, he (she) will enter "credential" information such as user name and password. Windows uses NTLM or Kerberos and other protocols to verify the user's credentials and let the user log in to the system. Applications typically use the system login product, or to achieve custom authentication as the basis for authorization. For more information on authentication, see Building Secure ASP.NET Applications in MSDN Library. Authorization - Use the authorization techniques described in this guide to deal with the threat of data tampering and information leakage. Identification of stream-across multiple computer deployments, sometimes need to pass information on the user ID through the verification between the computers in the system. If authentication is performed in the first computer, other application logic resides on a separate computer, usually uses the identification stream. For more information on the identification stream, see the designed stream designed to authorize later in this guide. Audit - Record authorized and unauthorized operations to reduce the threats brought by deny. This guide does not provide a detailed introduction to the audit. For more information on review, see Building Secure ASP.NET Applications in MSDN Library.

For more information on Stride, see Designing for Securability (English) in MSDN LIBRARY.

The model shown in Figure 2 illustrates how to reduce Stride security threats in multi-layer applications.

Figure 2: Security model for multi-layer applications

Figure 2 depicts a deployment of a plurality of physical layers, however, many smaller applications are completed on a physical layer, which simplifies authentication, authorization, and identification stream. Figure 2 contains the following measures to reduce security threats:

Reduce the rejection service (DOS) attack by bandwidth limit. This prevents malicious applications and users from continuously unpopened interference, thereby avoiding problems with applications. Use encryption to ensure communication security. Authentication can prevent identification spoofing. Authentication Vertical voucher based on the data repository. The application layer is used to use the identification stream (optional). By reviewing to ensure deebility. By authorization to deal with the threat of tampering and leak data.

Select authorization mechanism

You can use a variety of licensing mechanisms to control the functionality of the application, so that it operates in an expected manner or is not intended to be misused. These authorization mechanisms include the following:

System Authorization - Windows Using Access Control List (ACL) protection resources such as files and stored procedures. ACL specifies which users can access secure resources. .NET Code Access Security Authorization - Code Access Security According to the source authorization code of the code to perform operations. For example, code access security determines the assembly of other assemblies in the .NET application based on the evidence standard. Application Authorization - Application Code Self-authorized User Operation. You can use these methods to create secure applications, as shown in Figure 3.

Figure 3: Select authorization mechanism

System authorization

System Authorization is an object (such as printer, file) for operating system (such as printers, files) to set resource privileges or ACLs. The system administrator is responsible for maintaining these settings. System authorization is a non- "Yes" decision mode: the user is either authorized to access the resource or not authorized access to resources.

Examples of system authorization include:

Based on Microsoft ASP.NET application authorization settings to restrict access to the URL file or path specified in the web.config file. Permissions settings in the Active Directory® directory service. NTFS file system access control item. Message queuing privileges. Permissions granted in server products such as Microsoft SQL ServerTM. Such permissions may involve various objects, such as tables or views.

For more information on system-level security and licenses, see Building Secure ASP.NET Applications in MSDN Library.

System authorization can apply constraints for various objects, and restriction code needs to be licensed using .NET code access security.

.NET code Access security authorization

.NET Public Language Rules use code access security to limit the executable code. Code Access Security is granted permission (called "Permissions Settings" to the application code based on the evidence. These evidence may include the source, publisher or other evidence, such as the stringent name of the assembly.

Permission settings allow you to control the operations that the application can perform, such as deleting a file or access the Internet. For example, you can limit applications to use only quarantine storage units or control print access.

Regardless of the user's identity, the code access security only considers evidence, even if the user with the user uses the application, the code access security permissions remain unchanged. For example, if the code is from the Internet, no matter who the user is, the limit of its application (such as the ability to delete files) remains unchanged.

Applications for code access security include:

Limit the operational rights of downloading components and place them into an isolation environment to prevent the downloading component from performing hazardous operations. Isolation helps prevent fraudulent code damage system. Create an isolation environment for the host code running on the web server or application server. Restrict the operation of the components to prevent malicious code from being misused.

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

For more information on code access security, see the Code Access Security in ".NET Framework Developer's Guide" in MSDN Library.

Code Access Security By checking code permissions to ensure system security, it may also need to use application authorization to check user permissions, depending on the application.

Application authorization

Most applications achieve different functions or security permissions based on user interaction activities of users. Design "Application Authorization" refers to the user role in the program, implements a business rule or restricts users' access to the application resource.

The main purpose of application authorization is to protect features and other intangible content, such as business logic. Therefore, it is difficult to use the current system-level technology to implement application authorization, as these technologies need to use the settings for physical resources, such as ACLs. For example, you want to ensure the safety of approved operations for employee costs, but there is no physical resource to be protected, so when you design an application authorization, you should focus on high-level operations, not a variety of resources. The application authorization provides another system authorization method when the system authorization mechanism classifies too much or regardless of the application's data and status. For example, if the system-level security standard for XML Web Service is still in the development phase, it is still developing rich, then you can add security settings or create secure XML Web services to XML Web Service after the standard formation is returned. For XML Web services currently created, you can implement application authorization, protect the call to the service using a security socket layer (SSL) or other combinations.

Examples of application authorization include:

Check if the user has permissions to perform specific operations in the application (such as approval cost applications). Check if the user has access to the application resource (such as retrieving sensitive data columns from the database).

In the back section of this guide, you will learn how to design these applications authorization and how to write related code.

Entrance examination

In order to prevent operations from being continuously executed continuously, it will eventually fail, and you should always be authorized for each request for the user as soon as possible. Each authorization point is called "see a door". Examples of such a door mechanism include files and URL licenses in the ASP.NET entrance. In the process of identifying the flow to each hierarchy, there may be several "doorkeepers". Checking at the door can reduce the number of authorized inspections necessary in the system deep (after the entry point or door).

Objects in the system are executing authorized inspections require fewer authorization failure compensation logic. Single components are not responsible for handling the authorization failure without throwing an exception to notify the capture of the failed.

Use role to execute authorization

.NET Framework provides role-based applications authorization capabilities. "Role" refers to a class or a group of users sharing the same safe privilege.

Use the role instead of a particular user ID with the following advantages:

When changing (such as adding users, lift users or user weight), it is not necessary to change the application. Maintenance The permissions of the role are easy to maintain the permissions of each user. For example, processing 10 roles is easier than processing 120 users, and saves time. A user can have multiple characters, which enhances the flexibility of allocation and test privileges.

Define roles based on business organization

The role can represent the status of the user in the organization, for example:

Manager Employee ClaimApproValDepartment

One advantage to use this method is that information can usually be reused from a repository (e.g., Active Directory). Normally, these roles are useful when modeling actual business needs.

Not related to changes in the organization

You can also use roles to point out which type of operation is performed by the user. Such a role can link the functionality of the application to each user, for example:

CanApproveClaim CanaccessLab CanviewBenefits

The second method is more flexible, because you can design roles around the function of the application without having to consider the structure of the organization, but it may be more difficult to maintain the structure of the role. In most cases, you need to use these methods in your application.

Do not use role execution authorization

Sometimes you must use the user who is the authorized basis without overemphasizing the role played in the application. For example, you might want to implement only the service application allows the department manager to approve the employee's cost application, and to achieve this authorization level, the current user can compare the manager of the employee of the application. Use roles based on .NET-based applications

.NET Framework provides role-based security settings in system.security.principal namespace, you can use this implementation to authorize applications. To use an application authorization in .NET Framework, create iIdentity and iPrincipal objects to represent users. IIDENTITY package is a user ID, iPrincipal, is a combination of user ID and user role.

Figure 4 shows the relationship between IIDENTITY and IPRINCIPAL objects.

Figure 4: Relationship between IIDENTITY and IPRINCIPAL objects

Please note the following points in Figure 4:

The Iidentity object is an instance of the IIDENTITY class. The Iidentity object represents a specific user. The Iidentity interface has Name, isAuthenticated, and AuthenticationType properties. Implementing the IIDENTITY class typically also contains other private members with specific purposes, for example, the WindowsIdentity class encapsulates the account token of the user who is running code. IPrincipal objects are instances of classes that implement iPrincipal. The iPrincipal object is a combination of IIDENTITY that represents the user and its role. This allows individual authentication and authorization. IPrincipal objects use the Isinrole method to perform authorization and provide access to IIDENTITY objects through the Identity property.

Use identification

.NET Framework provides four classes that implement the IIDENTITY interface:

WindowsidentIndIndity GenericIdentity PassportIndIndity Formentity PassportIndIndity Formentity PassportIndity

Each class allows you to use different kinds of user IDs. To access the current WindowsIdentity object for an application using Windows authentication, you can use the static getCurrent method for the WindowsIdentity class, as shown in the following code:

You can also create a custom identity class by implementing the IIDENTITY interface in your own defined class. For more information on creating custom ID, see the extended default implementation later in this guide. For more information on how to use the default IIDENTITY implementation, see the design of the design for authorization for authorization.

Use subject

The .NET Framework provides a link user role and an IPRINCIPAL interface. All managed codes that perform applications authorized should use objects that implement iPrincipal. For example, the WindowsPrincipal and GenericPrincipal classes provide built-in iPrincipal implementations. Alternatively, you can also create your own custom principal classes based on iPrincipal.

To improve coding efficiency, you can use the technology described in this guide to authorize the technology described in the Authorized Authentication section, link the iPrincipal object to thread by using the static currentprincipal property of the Thread object, so that the current thread can easily access iPrincipal Object, as shown in the following code:

Then, you can test whether the user belongs to a particular role to perform an authorization check. To do this, ISINROLE methods of the iPrincipal interface can be used, as shown in the following code:

ASP.NET Application Handling the method of iPrIncipal objects is different from other .NET-based applications. ASP.NET creates a session look through the stateless HTTP protocol. As part of the session, all code to perform user requests can use the IPrincipal object that represents the user through the User property of the HTTPContext object. After the global.asax file has an onAuthenticate event, the public language freight library uses the httpcontext.user value to automatically update Thread.currentPrincipal. ASP.NET applications typically perform an authorization check using the User property, as shown in the following code:

Note: Manual changes

HttpContext.user will automatically update all threads performed in the same HTTP context environment.

Thread.currentprincipal. But change

Thread.currentPrincipal does not affect

HttpContext.user properties, it only affects threads selected for the rest of the request.

For more information on creating your own iPrincipal type, see the extension default implementation later in this guide. For more information on how to use the default iPrincipal implementation, see the design later for authorization for authorization.

Grant permissions using IIDENTITY and IPRINCIPAL objects

Using the IIDENTITY object is a sensitive operation because information related to the user can be used in this operation. Allow applications to change the current iPrincipal objects should also be protected because application authorization capabilities are based on current subject matter. The framework requires these operations with code access security permissions, providing protection. Use the Caspol.exe or .NET Framework Configuration Tool to grant SecurityPrIncipal permissions for applications that need to manage these objects.

By default, all local installed applications have this permission because they are running under "fully trusted" permission settings.

Do the following methods requires ControlPrincipal permissions:

Appdomain.SetthreadprincipalPolicy () Windowsidentity.getCurrent () WindowsIdentity.impersonate () thread.currentprincipal ()

For more information on setting up security permissions using Caspol, see configuring security policy for the MSDN Library (Caspol.exe).

Differences between managing authorization between Windows and Public Language Rules

The public language launch has a separate security structure above the Windows security structure. The Windows thread has a token of a Windows authorized user, and the runtime thread has an IPrincipal object that represents the user.

Therefore, when developing the code, there must be at least two types of security contexts that represent users. For example, an ASP.NET application that uses form authentication: By default, the ASP.NET process runs under the Windows service account called "ASPNET" (designed for user accounts created for applications). Assume that there is a user named BILL logs in to the Web site. The thread.currentprincipal property represents the user BILL of the Form authentication. The public language freight library sees the thread running with BILL, so all managed code regards BILL as the main body. If the managed code requires access to system resources (such as files), the ASPNET Windows service account can be seen regardless of the value of Thread.currentPrincipal. Figure 5 illustrates an authorization relationship between a common language freight library and an operating system thread. Figure 5: Authorization relationship between public language freight library and operating system thread

Simulation allows you to change the operating system thread in the user account executed during the interaction of Windows. You can simulate the Windows ID by calling the WindowsIdentity.impersonate method. This simulation form allows you to access local resources as specific users. When calling the Impersonate method, you log in with the user represented by WindowsIdentity. You must have access to user credentials in the server and have access to the Logonuser API. However, the process of manually creating WindowsIdentity is more complicated, so it is best not to perform analog if it is not necessary.

After the application code simulates other users, the WindowsimPersonatationContext.undo method restores the user ID to the original identity. These functions must generally be called, as shown in the following code:

For more information on simulating a Windows account, see Impersonating and Reverting in MSDN Library.

Note: In Windows 2000, call

The process of the LogonUser API must have SE_TCB_NAME privileges. For more information on verifying user credentials, please refer to the article Q180548

HOWTO: VALIDATE User Credentials On Microsoft Operating Systems (English),

Microsoft Knowledge Base (English).

Designed to authorize authentication

Authorization depends on authentication, that is, you must authenticate the user or process before you can authorize it to view or use protected resources. This section will analyze two authentication mechanisms and explain the impact of these two mechanisms on authorization:

Authorization according to Windows Authentication Authorization According to Non-Windows Authentication

Which authentication mechanism is selected is usually affected by a factor-independent factor, such as the availability of Windows user accounts, as well as some common environmental issues, including the client's browser type. However, the authentication mechanism you choose does affect the way you perform authorization.

Authorization according to Windows Authentication

All applications are executed under a Windows user account called "Windows Identity". During the Windows authentication process, you will perform your authorization check using the roles of this Windows user account or Windows user. Windows selects a user account based on the credentials provided by the following techniques:

Use the information provided when you log in to your computer Use the service account created for the application through configuration tools (such as component service management utilities).

The entire process of authorization using Windows authentication is: Windows uses NTLM or Kerberos to verify the user's credentials. For more information on using the Kerberos commission, see "How to: Implement Kerberos Delegation for Windows 2000" in Building Secure ASP.NET Applications (English). If the login is successful, a Windows Access Token will be generated, and the .NET application is encapsulated in WindowsIdentity. The truth is usually automatically set for WindowsPrincipal objects that contain Windows Role Concepts, but in some cases you must set up the method described later in this section. You can now use Thread.currentPrincipal to authorize. When you call the application logic remotely, sometimes you need to manually provide identification information to the caller. The implementation manual identification stream behind this guide will discuss this problem in detail.

Note: First

IPrincipal objects link to threads, then

Thread.currentPrincipal property retrieves the main body or identification information. This allows you to maintain a role set in memory, thereby reducing the frequency of finding such information.

Execute authorization using Windows role

You can use the WindowsPrincipal object to see if the user belongs to a specific Windows user group (for example, " / users"). The WindowsPrincipal object has an Identity property that returns a WindowsIdentity object that describes the ID of the current user.

You can configure the .NET application stored in the ASP.NET to automatically access WindowsPrincipal from the Thread.currentPrincipal property by enabling Windows authentication in Web.Config. You can use this technology in the ASP.NET web application, XML Web Service, and the .NET Remoting object stored in ASP.NET.

Other .NET applications, such as Windows services, console, and Windows-based applications, you need to use one of the following methods to create thread.currentprincipal:

Call SetPrincipalPolicy Settings CurrentPrincipal

Note: Use

IIDENTITY and

The code of the iPrincipal object must have

ControlPrincipal permissions, please use code access security to grant this permissions for the application. For more information, please refer to the front of this guide

Use roles based on .NET-based applications.

Call SetPrincipalPolicy

The setPrincipalPolicy method for AppDomain objects can link specific types of iPrincipal objects to the application domain. Please use the PRINCIPALPOLICY enumeration type of WindowsPrincipal, link the current WindowsPrincipal object link to the application thread, as shown in the following code:

Then you can authorize the subject. When starting an application, call SetPrincipalPolicy to ensure that the iPrincipal object is linked to the thread before performing any authorization check.

Do not use SetPrincipalPolicy in the ASP.NET application, as the ASP.NET authentication will manage this value during the Application_AuthenticateRequest event handler defined in Global.asax. Note: When there is no default entity in the application domain,

SetPrincipalPolicy is only valid.

Set CurrentPrincipal

To set the currentprincipal property, you must first create a new WindowsPrincipal object, the method is to pass the WindowsIdentity object to the WindowsPrincipal constructor. Then link the new WindowsPrincipal object to the Thread.currentPrincipal property, as shown in the following code:

Then you can authorize the iprincipal object.

For more information on how to perform an authorization check using WindowsPrincipal, see the execution authorization check later in this guide.

Execute authorization to execute the role defined by the application

To create an authorization check based on the role defined by the application (such as CANAPPROVECLAIMS), you must manually create a universal or custom iprincipal object. You don't need to call the setPrincipalPolicy method because its default settings are Noprincipal, which is the correct setting of your own body.

In most cases, the GenericIdentity object is created according to the user name that has been verified. (By using the Name property of the IIDENTITY interface, you can get the username.) This allows you to avoid security issues involving the user login token (accessible to the user login token) when providing IIDENTITY objects to other components. You can then create GenericPrincipal, connect the IIDENTITY object link to your own application defined role list.

The following code shows how genericIdentity and GenericPrincipal objects are created when using Windows authentication:

In most cases, the role defined by the application should be retrieved from the data repository, rather than writing code for role, giving greater flexibility when specifying role members. For examples of using this method, see How to build GenericPrincipal in the appendix using SQL Server.

For more information on how to use GenericPrincipal to perform an authorization check, see the execution authorization check later in this guide.

Authorization according to Non-Windows Authentication

You may not want to execute the application authorization using Windows authentication. This happens may be that the user does not have a Windows user account, or because of technical restrictions, Windows authentication cannot be used to verify the user's credentials.

Non-Windows Authentication is the process of verifying user credentials using non-Windows technology. This authentication includes .NET Framework to provide you with verification (such as ASP.NET Form authentication) and the authentication method you created yourself.

The entire process of authorization using non-Windows authentication is as follows:

The application collects user credentials. Application verification credentials are usually referred to with a custom data repository (such as SQL Server database). Starting to set the Thread.CurrentPrincipal property to the genericprincipal object that does not contain any roles. Then use the new genericPrincipal object, or replace Thread.CurrentPrincipal with custom class objects that implement iprincipal to provide the role of the application definition. You can now use Thread.currentPrincipal to authorize. When the application logic is called remotely, you need to manually provide identification information to the caller. Common non-Windows authentication types are:

ASP.NET Form authentication - ASP.NET Form authentication automatically creates a FormSIDENTITY object, represents the verified identifier. This verification contains a FormsAuthenticationalTicket, providing information about user authentication sessions. The Form Authentication Provider creates GenericPrincipal according to the FormSITITY object, but there is no role member relationship. For more information on how to use ASP.NET Form authentication, see article Q301240 How to: Implement Forms-based Authentication in Your ASP.NET Application By Using C # .NET (English), located in Microsoft Knowledge Base (English). Form authentication is almost always using application specific credentials. For examples of how to verify the obtained Windows credentials using the form authentication method, see Articles Q316748 How To: Authenticate Against the Active Directory by Using Forms Authentication and Visual C # .NET (English), located in Microsoft Knowledge Base (English) . Passport authentication - ASP.NET applications can perform authentication using .NET Passport. Passport authentication generates a PassportIndentity object representing the user ID. The PassportIndentity object extends the basic IIDENTITY interface to include Passport configuration file information. The Passport Authentication Provider creates a GenericPrincipal based on the PassportIndEntity object, but there is no role member relationship. For more information on Passport authentication, see The Passport Authentication Provider in MSDN Library. ISAPI Authentication Solution - is an alternate method that uses HTTP headers to implement manual or custom authentication mechanisms, such as the authentication mechanism in Microsoft Commerce Server. For more information on security settings in Microsoft Commerce Server, see Commerce Server Security in MSDN Library. HTTP Transport provides information for building universal or custom IIDENTITY objects and iPrIncipal objects (such as cookie).

For more information on ASP.NET authentication technology, see Authentication in ASP.NET: .NET Security Guidance in MSDN LIBRARY. All non-Windows authentication types listed above involve GenericPrincipal objects or custom IPRINCIPAL objects. For examples on how to link GenericPrincipal to the role defined by the application definition, see How to build genericprincipal using SQL Server in the appendix.

Designed for license

Authentication Create IIDENTITY and IPRINCIPAL objects for authorization and determine how to pass identification information to remote deployment on other computers to other computers. The transfer process of the identified identity that has been verified is called "identification stream". There are two ways to realize the stream:

Automatic identification flow manual identification stream

Use automatic identification stream

If all the code that requires identification information is performed in the same context, the public language launcher will automatically provide an identification stream. When the caller and the invigible share the same application domain, they are in the same context. If the client code (called "caller") and the called component (called "caller") runs in the same context, .NET automatically uses the same threeRead.currentPrIncipal object to both. For situations where the caller and callers are in different threads, see the use of multi-threaded execution authorization later in this chapter.

Code examples performed in an application domain include:

All required code is included in the process within the process, and the ASP.NET Web site is not deployed remotely. Not remote deployment logic, a single-machine application based on a Windows Form.

Manual identification stream

Due to technical limits, manual identification streams are required when authorizing inspections cannot be performed without performing authentication. For example, use the .NET Remoting to call the remote component with the TCP channel. For more information on using channels in the .NET Remoting application, see Microsoft .NET Remoting: a Technical overview in MSDN Library.

If you are implementing your own identification stream, use the data different from the call code (called "separation"). If your component interface involves calling functions, and use parameter delivery data, use other ways to send identification information.

For example, if you are calling an XML Web Service using SOAP, do not send identification information as part of the message body, and put it in a custom SOAP header. At this time, the requirements for security are not as strict when processing code design issues. This separation method can increase the scalability, reuse and aggregation of the code interface. Doing so also allows you to change the method of sending identification information with the development of technical standards without changing the interface convention. Web Services Security (WS-Security) (English) specification describes this.

Note that the identification stream is different from the transfer credentials, and the latter is the high-efficiency re-authentication process on the server. In addition, you can also pass the encrypted credentials in the message itself, however, encryption needs to use a shared key or public key system, so it does not have any advantage of passing the credentials in this way.

Here are some of the best scenarios to implement the stream:

Use functional requirements and technical limitations allowing the most powerful authentication. Some identification streaming techniques involve storage and / or delivery confidential information, which is critical to the security of the identification stream mechanism. Encrypting confidential information or using secure channels to ensure the security of information. The class in the System.Security.cryptography namespace may help you. In addition, examples of "How to: Create A DPAPI Library" in Building Secure ASP.NET Applications are also available for you. Saving confidential information using techniques such as data protection API (DPAPI). For information on DPAPI, see Windows Data Protection in MSDN Library. Make sure your implementation allows your review to reach the desired depth. For more information on review, see Monitoring and Auditing for End Systems in Microsoft TechNET. Pass the identification information in a trust environment

In the trust environment, the caller is handed over to the caller. At this time, it is considered that all information we passed from the caller to the caller is safe and reliable. For example, the web layer is a caller, and the components in the internal application are called by the caller.

Note: This solution will be unsafe if the illegal user can call other (and potential false) identity. To prevent such fraud attacks, use the technology provided by the system layer to protect the Secure Sockets Layer (SSL) or IP Security (IPSec) communication channel, and use code access security to ensure that only the corresponding code can call you. function.

In a trust environment, two methods are used to pass identification information between application layers:

Only pass the username - the caller only passes the user name to the caller. Then, as mentioned earlier in this guide, the caller queries the authorized repository, creates a universal or custom IPrincipal object, and connects the object to the thread. This method can also be used when you pass the identification information to the database. For more information, please refer to this guide execution authorization behind the data layer. This method is more flexible because there is no need to force the caller to deliver specific types of objects or additional information, such as application roles. Passing the role (using the iPrincipal object) - After verifying the user ID, the caller passes the role to the caller by serializing a universal or custom iPrIncipal object. Then, as mentioned earlier, the caller is retrieved, and the object is connected to the thread. This is the same as the effect of automatically occurring in a single application domain. . By passing a custom IPRINCIPAL object, you can pass any additional information (such as user profiles), such as user profiles), and identifies. However, IPrincipal objects that cannot be transmitted have been encapsulated. For example, WindowsPrincipal or all other subjects based on WindowsIdentity objects are not possible, as the tokens included in these identification information are meaningless other than their original environment. For more information on serializing the iPrincipal object, see How to Enable Authorization in the Appendix in the .NET Remoting component.

Note: Only in the trust environment using secure communication channels (such as a company LAN that uses firewall protected) can only be passed, so that network data is intercepted or modified on the network.

Pass the identification information in the non-confident environment

Non-trust environments refer to the case where the adjuster does not trust the called being called. In a non-confident environment, the called must verify the caller and then execute authorization, such as the web application to verify all the requests of the browser. There are two common methods to pass the identification information between the application layers in the non-confident environment:

Passing the signature data - transmitting encrypted signature data using the public key structure is an effective way to pass the logo stream. This method is usually used with asynchronous communication because there is no authentication session. Passing the signature data includes digital signatures for messages. Digital signatures are calculated based on the sender's private key and message content. To achieve verification, the caller obtains the sender's public key through the key management system, and uses the key to determine whether the sender uses the corresponding private key when signing the message. The SIGNEDXML class provided by .NET Framework can be implemented as an XMLDSIG standard. This standard does not involve issues such as key management or key trust. The recipient does not have to assume the degree of trust of the key used by the process, which is responsible for the application code. For more information on the XMLDSIG standard, see XML-Signature Syntax and Process on the W3C website. See Capicom SDK for how to use the code example of the SIGNEDXML class. CAPICOM is a Microsoft ActiveX® control that provides a COM interface to Microsoft CryptoAPI. This code example illustrates the entire process of using certificate authorization, signing, and verifying the XMLDSIG signature. You can find the code example from Platform SDK Redistributable in the Samples / C_Sharp / XMLDSIG directory: CAPICOM 2.0. For more information on CAPICOM, see Capicom Reference in MSDN Library. Pass the Token - Pass the token will pass some information, and the caller to verify this information to determine the user ID. Pass the token requires the use of shared authentication mechanisms or determining token validity. Pass the token may include passing a Kerberos bill between components. Another example is that the Internet Information Service (IIS) application in the e-commerce website is created by authentication cookies. When each browser issues a call command, cookies will pass back to the web server, which is a typical ISAPI solution.

Above you already understands how to implement authorization using various authentication mechanisms, and how to pass the authorization data between layers, the following will show you how to authorize you at the enterprise application.

Executive authorization in the enterprise application

Most applications have benefited from multi-layer design because multiple levels can provide scalability, flexibility, and improve performance. Although the authorization purpose of the application layer is the same (control user access system function and data), the design methods and implementation methods of each layer are not the same. The three layers in the enterprise application are:

User interface layer business layer data layer

Perform authorization in the user interface layer

This section describes how to perform authorization in the user interface layer. The following topics will be described later in this guide: Authorization is performed in the business layer and execute authorization in the data layer.

Perform application authorization in the user interface layer helps ensure that only authorized users can view and modify data, or perform business features associated with specific positions (such as pay-related operations). For the process of authorizing the other layers of the system, the user interface is authorized to limit the first level of access to these processes.

To achieve the following purposes, create an access check at the user interface layer:

Enable or disable the control according to the user's role member relationship, display or hide the control. For more information, see Change the controls in the form behind this section. According to the user's role member relationship, the flow is changed from one form (or page) to the next form (or page). For more information, see changing the page stream behind this section. When you create an authorization code in the user interface layer, use the best solutions:

As long as it is possible, configure the system authorization to control the input of the user interface. For example, configure the web.config file in the ASP.NET application, allowing only authorized users to access the input page. For more information on ASP.NET URL licenses, see Building Secure ASP.NET Applications in MSDN Library. The user is authorized to prevent the user from using the form or page to prevent the user from accessing the user interface element when an error occurs in a process or task. For example, it is required that the user can complete the operation after filling out multiple web pages in the ASP.NET application. If the user is allowed to enter the URL directly in the browser, it is possible to enable the user to access the page that is unauthorized access to a particular phase. Therefore, the application authorization check should be performed when loading the page. Do not only build the system's security settings on the application authorization in the user interface. To perform other access checks in the business layer and data layer, because these components may be called in a variety of ways or from different applications. If the user interface limits the data that the user can view, do not read unnecessary data from the data source, which avoids protected data to be leaked in the network transmission.

Note: All code examples in the following topics are as an example of a web form. Can pass

User.isinrole changed to

Thread.currentPrincipal.Isinrole makes the code for Windows forms. related

For more information on the ISINROLE method and the execution of an authorized check, see the back of this guide.

Execute an authorization check.

Change the control in the form

In Windows Forms and ASP.NET applications, it is possible to need to change the visibility of certain controls or disable them based on the display of the authorization change control in the user interface.

For example, in an application for employee cost applications, members of the CanApproveClaims role need to use a button to approve the application in the form, and all users who do not belong to the role can not see this approve button. The following code illustrates the method of implementing this:

If the user interface is more complicated or there are many custom roles, the above too simple method will result in the "if-kilse" statement chain when creating an authorized code.

You can use the following techniques to reduce this complexity of the display control according to authorization:

Merger Logic - Place the logical logic of the control in the private method called from the form's LOAD event. In this way, only the form authorization logic of the display control is saved with one position. The following code shows how to apply this method for web forms:

Use repeater controls when necessary - If the control corresponds to multi-wire data, you can use the repeater control to modify all control settings at the same time. For example, if you have created a Web form using a DataGrid, you can use a check box template column, allowing authorized users to approval multiple applications. The following code illustrates how to use this technology to display the AppRove column in the DataGrid.

Using the Model View Controller Mode - Model View Controller Mode can help you separate logic for controlling user interface elements from controls from controls. In the cost application example, the form can contain an employee list box and a show clalims button. When you press ShowClaims, you can force a clear logically separation by placing all the code you should perform in another function (called the controller function), even in another class. The list box acts as a view of employee data, the Show Claims button handles user operations (such as "click" and calls the associated controller function. The controller function is a method on your Web or Windows form that contains logic that chases the business data status and user interface status. The license code for changing the control status after loading the form is placed in these controller functions, not in the event handler. Use a separate form for each role - if the number of characters is relatively small, and each role requires a completely different form, you can create a separate form for each role. Test the role membership in each form and redirect to the correct form. This may increase a large number of testing processes, but you can use the model view controller mode of the previous description to reduce the workload of this, and can also reuse the display code. Change the page flow

Sometimes (for example, the user interface of the typical wizard) is required according to the user's role member relationship, requiring the user to complete multiple forms (or pages) to perform business processes. This method can change the order of the page or "stream".

In the previous application example, GeneralManager members can view and approve employee applications for all sectors, while StoreManager members can only view their department's employee application. In order to enable the GeneralManager member to select a department, you need to create another step to retrieve this information, then display the employee selection form.

The following code illustrates the method of creating this page stream. This code uses the ASP.NET Server.Transfer method to pass control to different pages. The call to Server.Transfer is included in the private method called DisplayNextPage:

Executive authorization at the business layer

The business process can be very simple business logic, or a large, running time, a workflow that contains many trust and non-credit partners. Business layer code must ensure that all customer requests can meet organizational rules and logical rules.

You have the following needs, create an access check in the business layer:

Authorization is performed on the operation of executing business processes. Before calling the internal business components, the call from the outside, the non-credible source is authorized. To do this, you need to create an iPrincipal object for business processes in the license process. Use the service interface management ID when you log into the business process, or to authorize the call to the internal business components, or use both methods simultaneously. An elimination of other parts of a distributed system or an external service that is not belonging to the application. To this end, it is necessary to manage the identification stream from the components. Use the service agent to ensure that the current user can perform an external call and / or can process the identity outside of the identifier overflow process.

When you create an authorized code at the business layer, use the best solution:

Decompose the authorization capabilities to the framework and utility components, such as custom iPrincipal objects. This will allow you to create authorization capabilities independent of business logic. Execute an authorization check at the beginning of the high-level process. This can be authorized in less location to reduce maintenance workload. However, to make the solution more secure, you need to perform authorization in each method that can openly access, because the call to these methods may not pass the authorization check.

Compare with role-based security settings in .NET and COM

COM The most famous feature is to provide an enterprise functionality such as transaction components, asynchronous activation, and object mergers. If you want to use these features in the .NET Enterprise Application, you should use the role-based COM security settings without using a role-based .NET security setting. Role-based COM security system and role-based .NET framework security settings cannot be operated. Therefore, in the initial design of the design, you must determine the components and .NET type components that reside in COM , otherwise it will be difficult to change the authorization code. For examples on how to determine the role-based .NET security system and role-based COM security systems, see Unify The Role-Based Security Models for Enterprise and Application Domains with .NET (English) in MSDN Magazines.

In addition to role-based security settings, COM has the ability to deliver Windows users context and the previous call information.

Note: It is not safe to mix the role-based COM and .NET security settings in the components. Since Windows is switched between managed code and non-hosting code when executing hosting COM components, it causes important information unreliable.

For role-based COM security settings code examples, see How to Use System.EnterpriseServices roles based on the Appendix COM security settings. For more information on using COM in .NET applications, see Understanding Enterprise Services (COM ) in MSDN LIBRARY.

Execute authorization in business logic components

Components containing business logic usually requires an authorization check. You can use the service interface of the .NET Remoting or Package Traffic Components (such as XML Web Service) to call these components directly from the user interface.

The license logic you create is often mixed with the component business logic and becomes part of the component business logic. For more information on how to separate business logic and authorization logic, see Separation Business Logic and Authorization Logic behind this guide. For more information on how to create an authorization check, see this guide to create an authorization code based on role .NET security settings later.

Executive authorization in the entity

Entity represents data, or may include some behavior. The entities that can be used have many, such as DataSet, XML strings, XML document object models (XML DOM), as well as customized entity classes in applications, which depends on the physical and logic design restrictions of the application. The application generates both entities and uses entities.

The entity often moves between the application layers, including the data source search data, and transmits to the user interface and returns the entire process of updating the data source.

You can create classes to represent entities that perform authorization checks. For example, users who belong to a role can create and initialize entity objects.

However, in most cases, the application authorization should not be performed in the entity because:

Pure data implementation (such as DataSet, XML string, and XML DOM) does not provide a built-in method for executing an application authorization check. Entities (including third parties provided) have high mobility. The client application is not necessarily capable of using entity authorization.

Execute authorization in the service interface

The service interface is a window that renders internal business logic to the external world. The service interface provides an entry point to the business process so that you can flexibly change the method of signing the internal process without affecting the external calorie.

The service interface provides an entry for its access to the internal business process components for non-credit or request authentication and authorization.

In an example of cost application, the service interface uses XML Web Service to allow non-credit client access to request processing components, using .NET Remoting or Distributed COM (DCOM) allows trust client access to request processing components. The service interface can also be a custom message queue (MSMQ) listener. See How to Perform Authorization in the XML Web Service in the appendix for explaining an example code to explain the XML Web Service.

Execute authorization in the service agent

The service agent is a bridge between business logic and external services. XML Web Service and MSMQ Message Queue are examples of two external service agents.

Access to external services can be controlled by authorizing the service from the service layer inside the business layer. The service agent acts as an external service, when the code is called external service, allowing you to perform verification, authorization, data formatting, and other tasks. Use the service agent to allow you to change the called external service and its signature without affecting your business logic. You can write code in the authorized service agent to prevent unauthorized users from calling external services.

Note: This authorization is different from the authorization of external services. If you keep using external services, you must perform an authorization check in the caller to ensure the security of the system.

In the following service proxy code, if the user does not belong to the CanApproveClaims role, he / she will not pass the ClaimxML message to the ApproveClaim XML Web Service method.

For more information on processing an exception of authorization code, see Processing Authorization Errors in this guide.

If the external service is required to use a special user ID, create a code in the service agent to deliver an acceptable IIDENTITY object to pass the identification stream to the component. For more information on the management identification stream, see the design of the design for authorization in this guide.

Execute authorization in the data layer

The data layer is the last line of defense, which is used to resist illegal requests from the user interface, business components, and attempt to access data directly. From an authorized perspective, the data layer ensures that only approved users can access and modify data regardless of their access.

When you need to do the following, create an access check in the data layer:

Prevent sensitive data from leaked into the data layer. Prevent unauthorized modification of existing data and insert new data. Use stored procedures or view to limit access to data, rather than modifying direct access to data tables.

To perform authorization in the data layer, you can use multiple technologies and objects, depending on your security requirements. Authorization can be performed in the following data layer components:

Data Access Logic Components - Data Access Logic Components are responsible for retrieving data from the database, saving the data back to the database, and is responsible for processing the logic requests required to complete the data operations. All application data is passed between the data access logic components in the database and other parts of the application. Stored Procedure - The stored procedure can perform authorization logic in the database and retrieve and update data. Database Security Features - Use SQL Server's built-in security features to protect database objects, such as tables, columns, views, and stored procedures.

For more information on using data access logical components and entities, see Designing Data Tier Components and Passing Data THROUGH TIERS (English) in MSDN Library.

The following questions can help you choose a data layer authorization policy:

How much is the authorization logic?

Simple - Perform an authorization check during the stored procedure. Complex - execute authorization in the data access logic component and call different stored procedures. What is the complexity of the stored procedure?

Simple - Perform an authorization check in the data access logic component and call different stored procedures (if you create multiple stored processes that do not increase the maintenance difficulty). Complex - execute an authorization check during the stored procedure, which provides parameters to the authorization check. If multiple stored procedures that create a similar operation increases the difficulty of maintenance, you can deliver a value to the stored procedure to reduce the number of stored procedures. How many stored procedures involve authorization check? Less - Create multiple stored procedures involving authorization checks. Create a naming standard that is clearly linked to stored procedures, such as GetClaimsmgr and getClaimSemp. But this method is unfavorable in the development of the application, so it should be used with caution. More - Create a plurality of separate stored procedures, retrieving different data depending on the different connected users. Connect to the database using a service account representing the application role, allowing the stored procedure to perform an authorization check. This approach minimizes the number of stored procedures, and thus also reduces maintenance workload.

When you create an authorized code in the data layer, use the best solution:

Connect to less service accounts to achieve optimal performance of the connection pool. When the connection information (such as user information) matches existing connection, the connection pool allows the application to reuse the connection. Therefore, it is not necessary to create a connection for each user. For more information on connection management, see "Managing Database Connections" in the .NET Data Access Architecture Guide (English) of MSDN Library. Protect the database object with GRANT and DENY permission. Refused to directly access the data sheet You can use an application (such as query analyzer) to prevent connections to the database without enforcing the business logic of the data. Only the allowable user / service account can access stored procedures and views. Always use the stored procedure when using an application authorization technology including a WHERE clause. This helps prevent SQL entraining attacks, and an attacker to implement such an attack will attach other (usually malicious) SQL statements into the legal WHERE clause. For more information on SQL entraining attacks, see Building Secure ASP.NET Applications in MSDN Library.

Execute authorization in the data access logic component

Data Access Logic Components are components that provide a functionality that provides functions prior to accessing the database. Therefore, you can take advantage of them to ensure that only authorized users can access or modify data.

When there is a case where there is an authorization in the data access logic component:

Multiple applications use the same data access logic components. It is necessary to protect access to the powerful functionality provided by the data access logic component or the data repository. You need to limit users access to sensitive data.

An example of using role-based security settings in a data access logic component includes: filtering data on data before data is delivered to other application layers, and control the stored procedure executed.

For more information on how to perform an authorization check, see the execution authorization check later in this guide.

Filter data in data access logic components

To ensure that appropriate information is returned to other application layers, you should selectively delete sensitive data in the data access logic component code.

The following code example deletes the confidentialnotes column of the data when the user does not belong to the Manager role.

Retrieving unwanted columns from the database is a waste of resources, especially those that are not needed. Instead, only the necessary data is selected using the stored procedure, and the performance of the database engine can be improved.

Call different stored procedures from data access logic components

You can create multiple stored procedures that return the correct data for one role. Then, the data access logic component code performs an authorization check, determines which stored procedures to use according to the user role.

For example, you can create a stored procedure version for Manager, create another different version for Employee, both of which are only different. Data Access Logical Component Code will check the user's role member relationship and call the correct stored procedure. The following code shows how the data access logic component method selects the stored procedure to be called according to the user's role member relationship. These codes use a secondary class to avoid excessive ADO.NET code. Microsoft Application Blocks for .NET (English) provides SQLHELPER classes:

Execute authorization during storage

There are two ways to perform authorization during storage procedures:

Transfer Role Sign - Perform an authorization check in the data access logic component, pass the authorized result flag to the stored procedure. This will allow the stored procedure to filter data according to the authorization flag, as shown in the following code.

Pass the user ID or other role information - Data Access Logic Components Transfer the user ID as a parameter to the stored procedure. Then, the stored procedure uses this parameter to find the user's role member relationship and select the data, as shown by the following code.

Execute authorization in the database

As the basis for security solutions as database security features. Then use the stored procedure design application to authorize on the database security feature, as described in this guide.

Execute Authorization with Database Security Features:

Use the SQL Data Definition Language (DDL) security statement, such as Grant, Deny, and Revoke, control the access to the table, column, view, stored procedures, and other data objects. Access to sensitive data with a possible lowest level (only data). SQL Server itself does not support low-level licenses, however, you can simulate low-level licenses by creating views and stored procedures, which will be introduced later of this topic. Strengthen safety as much as possible. Note that higher security reduces scalability.

Before performing authorization in the database, you must select the way the application is connected to the database.

Simplify management using SQL roles

When designing the system, you must consider simplifying the maintenance of SQL Server using the SQL Server role. SQL Server provides a variety of roles, including:

User-defined database roles - the role created by the unique sp_addrole stored procedure. You can then add SQL users to these roles using the sp_addrolemember stored procedure. Application role - a role created for an application instead of a Windows user or group. Fixed Database Role - Link to a fixed role of universal database features, such as SQL administrators and database creators: sysadmin and dbcreator.

For more information on SQL Server Security, Authorization, and Authorization Roles, see Building Secure ASP.NET Applications in MSDN Library.

Consider linking the application role to the SQL Server role, making the application and SQL Server management. Connect the service account that will directly map to the SQL role to the database to implement this link. This technology is introduced in the following section.

Connect to the database

To control access to tables, columns, views, stored procedures, and other data objects, SQL Server must recognize users who need authorization, which can be implemented by the following connection methods:

Windows Authentication - If you configure SQL Server to use only Windows authentication, you must perform the process of establishing a connection in the user context. SQL Server uses the Windows user account for all forms of authorization. This method provides the safest connection because it does not pass the credentials through the line. SQL Server authentication (hybrid security settings) - If you configure SQL Server to authenticate with SQL Server and Windows authentication, you can use Windows authentication, or use usernames and passwords to specify users in the connection string to specify users to authenticate. Whether connecting to the database in any way, you must first create a few service accounts representing the application role, and then grant permissions for each service account according to the role requirements.

For example, create a service account such as USR_Manager and USR_Approver to achieve the minimum privilege, that is, only part of the application functionality is allowed.

This approach brings certain inconvenience, because when you use Windows authentication, you need to access the logical component analog service account from the data.

For more information on managing database connections, see the .NET Data Access Architecture Guide in MSDN Library.

Control access to sensitive columns

Use the T-SQL statement or the SQL Server Enterprise Manager utility to apply Grant, Deny, and Revoke permissions in column levels, enable access control of columns. Please try to use this license technology because if the database is very large, the list of listed to maintain will be very long and very time consuming in actual operations. If you want to use this technology, use the service account when connecting to the database to make the maintenance work easily.

Control access to sensitive rows

SQL Server has no implies allow you to control access to each line. However, you can add security columns to the data sheet to create a control line. Safety columns can save a separate username or the minimum role you need to access data (assuming the organic form of the role is hierarchical). Safety columns allow you to limit access to each row, but if the user can access the data table directly, the technology will have no effect.

Access to each row can be controlled in conjunction with the security column function and the SUSER_SNAME function of the data table during the view or stored procedure. The SUSER_SNAME function will retrieve the username (very likely to be a service account name).

The following code shows how to create a view, which only returns the current user's row.

Note: This method requires you to use a separate user ID when connecting the database so that

SUSER_SNAME functions can retrieve correct information. In this case, the application will not be able to take advantage of the connection pool.

Create an authorization code using a role-based .NET security settings

This section describes how to use the role-based .NET security setting to write execution authorized code. Role-based security settings allow you to perform licenses for the entire user category or user set, not just to perform authorization for a particular user.

You must consider the following questions:

Perform an Authorization Check - To perform an authorization check based on role-based .NET security settings, there are multiple programming techniques available, and you must determine which technique for specific use according to your own application requirements. Separate business logic and authorization logic - this is important to have a strategy that separates business logic and authorization logic. Processing Authorization Error - You must determine how to handle authorization errors. Authorization errors not only affect your component code, but also affects the code to call the component. Using multi-thread execution authorization - If your application uses multi-threaded technology, you must determine how the iPrincipal object is the best combination of each thread. Solving this issue There are many ways to choose from, depending on how you process role-based licenses in multi-threaded applications. Extended default implementations - Some cases, it is very beneficial to expand the default implementation provided by the Class Framework class libraries in the .NET Framework class library. Executive authorization check

.NET Framework provides three ways to check if a host is a member of the role:

Manually check the command check declarative check

This topic will introduce you to these technologies one by one and provide guidance on its own use occasions. The above three technologies are the same as those of them use the ISINROLE method of the main body of the thread. Similarly, these three technologies also assume that the main body is automatically or manually chaind to the Thread.CurrentPrincipal property, as described in the design of the authorized authentication as described in the previous design.

However, there are some obvious differences between these technologies on the issue of checking if a host is a role. E.g:

Manual and command checks allow for complex checks including variables, which will be described later. Choose manual check or command to check it entirely on personal preferences. When the check just involves simply comparing a constant role value without including a variable or complex logic, use a declarative check is appropriate.

In these three ways, manually checking the role is the most common method.

Manually check the role

You can manually check if a user belongs to a role by calling the ISINROLE method of the iPrIncipal object. However, GenericPrincipals and WINDOWSPRINCIPALS are not the same.

Check the role using GenericPrincipals

When manually use GenericPrincipals to check the role, you must use a string to represent the role name. For example, the following code will check if the user belongs to the Claims Approver role.

Check roles using WindowsPrincipals

When using WindowsPrincipals manually checking the role, there are two different ways to represent the role name:

String - If you are checking custom Windows users created by system administrators, such as " / Claims Department" or " / Claims Department", use strings. For example, the following code will check if the user belongs to a custom Windows user group named " / Claims Department":

If it is a local computer level, use the Environment.MachineName property. When you deploy this property to other machines, you don't need to change the code. The following code illustrates the usage of the Environment.MachineName property.

Note: When you use string values ​​to check the built-in local Windows user group (such as Administrator or user), you must specify a word.

Builtin (such as Builtin

/ ), indicating that this is a special user group name.

Use the WhoAmi.exe tool to view the correct syntax of the user's Windows user group. WHOAMI.EXE tools can be obtained from http://www.microsoft.com/windows2000/techinfo/reskit/tools/existing/Whoami-O.asp (English). To display a complete list of user roles, specify / all switches when the tool is executed. Note: The role-based .NET security settings do not support Windows 2000 format "UserName@Domain.com".

WindowsBuiltinrole Enumeration Type - Use the WindowsBuiltinrole enumeration Type Check whether the role member relationship belongs to the built-in Windows user group, such as Administrator or User. For example, the following code will check if the user belongs to the built-in Windows User role.

This enumeration can simplify the process of localized code because the Windows installation environment does not affect the user group list.

Complex manual examination

Regardless of whether genericprincipal or WindowsPrincipal, you can perform complex access checks in the C # language by using multi-segment IF statements containing logical operators (such as logic AND&] and logic or [||]). The following code shows this check:

You can perform complex checks by combining operators, such as less than numbers (<) and greater than numbers (>).

The authorization fault is handled by throwing an abnormality. For more information on passing the license check fault, see the throw authorization abnormality behind this guide.

Ordinary check role

You can use the command check to force a certain user belong to a specific role. Command check of the user's role member relationship by creating a PrincipalPermission object and specify the desired role. Then perform an access check by the Demand method. If the body is not a member of the command role, the public language launch will generate a securityException.

The following code checks whether the subject belongs to the role CEO specified by the application.

Note: All examples in this topic are directed

User attribute

The PrincipalPermission constructor passed a

NULL value so that users belonging to the corresponding role pass through access. If you specify the username, the specific user will check when running, which will affect the purpose of the role.

You can use the following technology to command the role member relationship to check:

Implementing OR Solutions - You can use the Union method representing the OR solution to perform a complex check. The following code will check if the user is a member of the CEO or SENIOR Manager role.

Create an AND solution - perform two inspections in order, create an AND solution, as shown in the following code.

Use variables - you can use variables, domain names, and machine names, dynamically check the role name. This is similar to the method of performing manual examination, as described earlier in this topic. The following code will check if the user is a member of the Claims Department role, and the Environment.UserDomainName property gains the network domain name associated with the current user.

note:

There is also one of the PrincipalPermission class.

The INTERSECT method, but this method is not used for role check because the two users will never intersect. The reason for this method still exists is achievable

Use it when the Ipermission interface.

You can use standard exception handling techniques to process an exception generated when the Demand fails. For more information on dissemination authorization check failed, see Handling Authorization Errors in this section.

Declared check role

You can place PrincipalPermissionAttribute on classes, methods, and properties, disclose role permissions, as shown in the following code. Note that the member level property overwrites all levels of level properties. During the compilation process, the .NET compiler saves the PrincipalPerMissionAttribute as XML in the program collective data. Instantiate the PrincipalPermission object when the application is executed, and the access check is performed. Therefore, the functionality of the command and the declarative access check is similar.

Creating a proxy when running through an authorization check, no parameters are created, so performance will increase when the authorization check fails. If the check failed, the runtime will automatically throw System.Security.securityException, and the protected method code cannot be executed. Since the method is not performed, more complex authorization cannot be performed according to business logic, such as comparison parameter values.

At compile time, the value of the property will calculate the value of the property, so you must hardcode role in the metadata so that dynamic solutions can be implemented using values ​​such as Environment.MachineName. You can't use WindowsBuiltinrole enumeration because declarative checks are basic implementations for iPrIncipal.

If multiple PrincipalPerMissionAttributes are specified, these properties will be combined to form an OR solution. Therefore, as long as the main body is a member of a role, the authorization check can be successful. The following code requires the caller of the method belong to the CEO or Senior Manager role:

Note: You cannot use a declarative method to check if the user belongs to a list of roles.

Use declaration techniques help separate authorization codes to other business logics. Separating business logic and authorization requirements can improve the maintenanceability of code. After making this separation, do not change business logic when changing the license logic, thereby reducing the possibility of introducing business logic errors in your code due to negligence.

Separate business logic and authorization logic

Role-based .NET security framework is a simple definition of IIDENTITITY and IPRINCIPAL interfaces to enable developers to expand the interface to meet their needs. When there is a situation in the following cases, it may be necessary to expand this feature:

You need to save some additional information about users (not only usernames and roles) for the application requirements. For example, it is possible to save information such as organizational address code to illustrate whether the user is in a specific location. You need to use your own role-based security information source. The .NET Framework provides an implementation of Windows Retrieval Role Information (using WindowsIdentity and WindowsPrincipal class). If you want to maintain your own information repository, you usually need to implement custom extensions. There are special requirements for authorization. For example, you may need to write code related to deploying positions, which is an example of "external knowledge" to implement an authorization check.

Processing an authorization error

If the authorization check in the business process fails, the component code needs to notify the failed caller. The best notice method is to throw an exception. If you are implementing an asynchronous solution, processing such an exception can be taken as long as the method of processing a standard asynchronous exception is taken, for example, insert an exception in the abnormal queue in the abnormal queue when using MSMQ.

When you design the component, it is assumed that the corresponding authorization check has been performed at the "Door" in the trust boundary. If this hypothesis is violated, the component should throw an exception. For example, you can assume that the user interface does not allow the user to delete the file. When an application creates a user interface, a valid check is implemented at the entry, and the component that executes the delete file logic must follow this hypothesis.

Exquisite

When the application authorization check fails, you can throw the following types of exceptions:

System.ApplicationException - throws ApplicationException and prompting the application authorization check with a message to fail. If you will be authorized to check as a subset of business logic, you can use this exception type in your application. E.g:

System.Security.securityException - Throws SecurityException and uses a message to prompt the application authorization check failed. E.g:

This exception is automatically thrown when the command or declarative authorization check fails. If you think that the authorization failure will cause a secure violation, you can use this exception in your application. This anomaly type can be used to capture all of the security related exceptions in a CATCH handler. The code access security and other system-level operations will also throw this exception, which increases the difficulty of the caller filtration and the difficulty takes appropriate measures. Custom Anomaly - As mentioned earlier, using a declarative and command authorization mode, SecurityException is the default exception type. Return standard information at runtime: "Request the principal permission failed". You may need to add additional information based on a specific error to help callers handle exceptions in a particular manner. To do this, you can define your own custom anomalous classes to indicate different types of authorization errors that occur in the application. You can create a custom anomalous class benefit from the application as follows:

The call code defines a separate Catch handler for each exception type to handle errors in a particular manner. For example, calling code can filter an exception of a type and record them for implementation. If the authorization anomaly class is set correctly, you can reuse these classes in multiple applications involving an authorization check. A common license fault type can be combined to enable the process and components of mutual aggregation to perform the correct operation. For more information on creating our own exceptions and their implementation examples, see How to Create an Authorized Custom Average Type of Appendix.

Note: The propagation authorization exception should not contain any sensitive information that may damage the system. For more information on this information and other exception management best programs, see MSDN Library

Exception Management in .NET (English).

Processing authorization exception

In addition to the role-based authorization exception, calling code can also define the Catch handler for the authorized exception. The deployment scheme is different, and the form of the securityException violation you receive may also be different. For example, if you start the code from half-credible environment, you may throw an exception when running, indicating that the code access security permission (such as file access issues). Although these abnormalities are not associated with role-based authorization, it may cause SecurityException.

An exception handling code can be written to distinguish between roles-based authorized anomalies and other types of authorization anomalies. Check whether the exception is related to the role-based authorization using the SecurityException object, as shown in the following code:

The result of the PermissionType property allows you to filter code access security and role-based authorized anomalies. After filtering an abnormality, you can throw a custom exception or handle an exception within the caller.

Use multi-thread execution authorization

Most .NET-based applications use multithreading to improve responsive or asynchronous implementation. When using the subject, multithreading makes the problem complex because each thread must be linked to an IPrincipal object. Copy the iPrincipal object to all new threads created by the parent thread when running.

According to the following rules, the Thread.currentPrincipal property returns a different iPrincipal object:

This iPrincipal object will be returned if an IPRINCIPAL object is associated with a thread. If the IPRINCIPAL object is not explicitly associated, and the setthreadprincipal method is used, the default IPrincipal object of the application domain will be returned. Call AppDomain.currentDomain.SetThreadPrincipal methods, you can ensure that the current and new threads use specific iPrincipal objects when running. For ASP.NET, it is recommended that you do not use this option because the body is processed by runtime, and this option also affects other threads running by other users. Note: If this method is called multiple times during the validity period of the application domain, one will throw a

PolicyException.

If there is no IPRINCIPAL object or the default application domain IPRINCIPAL object with the thread association, aniprincipal type object specified in the SetPrincipalPolicy method is returned, as mentioned earlier. If you don't use the above method, a null (or Nothing) will be returned.

Extended default implementation

When expanding the .NET-based application authorization framework, follow the principles:

Implement IIDENTITY and IPRINCIPAL interfaces - this will ensure that your extension is compatible with other features based on roles (such as ASP.NET URL Authorization). Use delay initialization - if the task of importing role information is too time consuming to construct an iPrincipal object, this activity should be postponed, etc. When the first time you need information, it will be performed again. Adding an IPrincipal object to the execution thread - This will allow you to use the previously mentioned declaration, command, and manual authorization checks, and work with other technologies (such as ASP.NET authorization).

Determine expansion strategy

Decide to create the extension type and where to create it. Table 1 contains some common extensions and describes where to create additional logic required.

Table 1: Creating a location of an application authorization extension

Extended Type Customizes Customize the information x related to the host helper class user specified by X-related permissions or role x needs external knowledge X

Implement custom ID

When the feature provided by GeneralIdentity or WindowsIdentity object does not satisfy your needs, you should create your own class to implement iIdentity. The enhanced enhancements that may be generated include:

Manage tokens or user identifiers. This method is generally required when a package is required to relate to the identity verification process of the token. Windowsidentity, FormSidentity and PassportIdentity class management represents the token of the user. These classes use Microsoft Win32® tokens, Form authentication tickets, and Passport unique identifiers (PUID). For example, you can create your own custom ID when you use the ISAPI single login solution. Pack your own code in the iidentity object and use it to all applications. For example, PassportIndentity provides many additional properties and methods through standard IIDENTITY interfaces, including configuration information. These additional information can be added to your identification class using standard techniques (such as public properties). Another example is often necessary to authorize inspections based on the user's manager, and in this solution, you can use the identifier value to provide the user's manager.

Realize custom main body

When the feature provided by GenericPrincipal or WindowsPrincipal objects cannot meet your needs, you should create your own class to implement iPrincipal. The enhanced enhancements that may be generated include:

Implement your own role enumeration type, the method is the same as the WindowsBuiltinrole enumeration method used in WindowsPrincipal. The method of implementing this feature is to overreload the Isinrole method for call code to select whether you use your enumeration type or string. Check if the body belongs to a role in the specified list. For example: Access a list or enumerate the role to which the subject belongs. E.g:

Forced partial role hierarchy to enable some roles "greater than" or "less than" other roles. For example, Senior Manager "greater than" or higher than Junior Manager.

Repeated license implementation

If you are reused when you design a frame, you can reuse the license framework in multiple applications. Contents that can be reused typically include code and structure for implementing authorization capabilities.

Repeat the benefits of the application authorization framework:

Developers within your organization can use an application authorization framework as a work goal. Components that support the application authorization framework can be repeated in other applications because these applications use standard licensing methods. The authorization subsystem becomes a center with other systems or platforms. Reused the need to reduce the needs of the old application with the new application that requires the authorization data. Authorization management is consistent in multiple applications, and thus management and operators can perform the same job.

This section describes some of the best programs that reuse authorization implementations.

Create a reusable license framework

You can choose the number of applications authorized to reuse in your application. The options are:

Repeat an authorized database and an XML Web Service that accesses authorization data. Repeat the license framework, but each application uses a separate database instance.

Figure 6 shows an example of implementing an application authorization reuse.

Figure 6: Logical representation of application authorization reuse

Please note the following points in Figure 6:

Different applications can reuse the same licensing framework. Authorized services provide security access to authorized data. The central database saves authorization data. A management utility provides all configurations. Locally cache changes to authorization.

Table 2 describes the various components shown in Figure 6 and explains how to reuse these components in different items and different applications.

Table 2: How to reuse the authorization component

Component Description Repeated method Authorization Framework creates a custom code to support authorization capabilities, such as custom principles, identity, and exceptions. Create an assembly containing all custom, reused code for other projects. It is also possible to give a strict name for the assembly and install the assembly to the global assembly cache. Authorization caches a unit of optional saving authorization information, which is very close to the actual location where it is located. Create a HashTable object (similar object in the memory repository) using the appropriate method, and refreshed according to you. In order to improve efficiency, the iPrincipal object should use authorized cache retrieval role membership, not to enter the database. If you need to protect or hide the data in the cache, use encryption; otherwise, the data in the cache is signed to prevent data from being tampered with (if the data is stored locally or other vulnerable attacks, this is especially important). Authorized services to authorize the interface (or "Door") Create a process external component that runs in a secure environment that can be accessed. Process Each component can be used to authorize access to the repository, and the method is to check if the access is performed by the specified account, thereby preventing other users from accessing the repository. Alternatively, you can build a centralized XML Web Service that is the highest interoperability. Keep in mind the communication channel between the authorization service and the authorization framework. Managing Utility Application Administrators to maintain the user interface of the authorization data. Creating an administrator can adjust the central website of the authorization setting or create a reusable graphical user interface to deploy in each application. Authorized data authorization data schemes, stored procedures, and data access logic components use a database for all authorization data. In addition, all applications use standard authorization schemes. Guarantee implementation

In order to ensure the security of the reusable license framework, please follow the following principles:

The caller of the authorized data repository performs authentication checks to prevent unauthorized query authorization information. Use secure transmission, such as SSL or IPSec. Deploy an authorization service in a separate directory of each application, such as XML Web Service, which can be configured to play a role in deploying its application.

Improve performance of reusable licensing framework

Use the following technique to improve the performance of reusable application authorization framework:

Use batch authorization queries as much as possible to avoid frequent processes. For example, retrieve a role in multiple users with a request. Caches the authorized data to a location close to the memory repository (such as a HashTable). The cache can also reduce the dependence of the location and organization of the underlying repository. To improve performance and enhance safety, you should also set separate caches for each physical computer. A predetermined refresh or on-demand refresh. Realize the latency initialization of the authorized cache, avoid retrieving authorization information when the access check is not performed.

appendix

This appendix includes the following topics:

How to enable authorization in the .NET Remoting Component How to Perform Authorization How to Create Authorization Creating How to Create Authorized Customization How to Use SQL Server How to Use SQL Server How to Use SQL Server How to Use System.EnterpriseServices Role COM Safety Set

How to enable authorization in the .NET Remoting component

The .NET Remoting component does not automatically pass the body from an application domain to another, unless the two domains are in the same process. You must manually pass this information between the caller and the caller, and ensure that the information is in a safe state during the delivery process.

For more information on using Windows authenticated .NET Remoting, see the .NET Remoting Security Solution (English) in MSDN LIBRARY. When using non-Windows authentication, you can use the CallContext class and the ILogicalThreadAffinative interface to provide identification stream.

When the remote object call method, the CallContext class allows additional information. This information can be any information required by a single method, such as user information.

Only the type of ILOGICTHREADAFFINATIVE interface is sent to a server in a separate application domain. For example, you can create an easy type of ILogicalthReadAffinative, store IIDENTITY or IPRINCIPAL objects. Remote objects can access this object and you can check the role's relationship.

The following code shows how to create a class that implements the iLogicalThreadAffinative interface and contains iPrincipal-based objects.

The following code shows how the remote object uses the CallContext.getdata method to retrieve iprincipal information via the PrincipalStorage class.

The following code shows how the client application uses the CallContext.SetData method to set IPRINCIPAL information before calling the remote object.

The following code shows the server application that registers the remote object.

How to execute authorization in XML Web Service

In the following code, the ProcessClaim XML Web Service method performs an authorization check and throws an exception when the check fails. Check if the sender of the approved fee is authorized to be sent.

In order to ensure that the modulated by the processed has passed authentication, you need to specify the authenticated properties of PrincipalPermissionattribute. Doing so you can make sure Thread.CurrentPrincipal automatically provides the correct IPRINCIPAL object for command authorization checks.

The following code will call the ProcessClaim service. Only users in the EMPLOYEE role can submit employee applications to XML Web Service.

This code assumes that the user who has passed the verification belongs to the role defined by the application, which can be Employee or Contractor. For more information on how to load a role IPRINCIPAL object, see How to change the body in the ASP.NET application later and how to build genericprincipal using SQL Server.

How to create an authorized custom exception type

To solve problems or review, it is possible to throw a custom exception, which contains typical authorization failures and other information (eg, user names or email addresses that cause exceptions). The following code will create an exception class to handle the failed authorization. This exception class includes username from Thread.currentPrincipal.Identity.

The following code will call the components of the execution authorization check. If the check fails, the Catch block will test an exception and display the username via ApplicationAuthorizationException.

The following code will be used as a caller component that performs an authorization check. This code has been specially designed to refuse to access a specific file so that there is an unrelated annexeed with authorization. Catch blocks filter two possible exceptions using the PermissionType property.

How to change the main body in the ASP.NET application

You can change the default IPrincipal object in the ASP.NET application to include an application-specific role loaded from the data repository after identity verification. After changing the iPrincipal object, you can continue using the application-defined role to authorize check and can still rely on any type of authorization. It is best to change the IPrincipal object in the Application_AuthenticateRequest event handler because you can use the verified identity, and the event handler is performed before the web page or XML Web Service logic. The following code uses GenericPrincipal objects in accordance with the verified identification to replace HTTPCONCIPAL objects and adds objects to HTTPContext.cache to improve performance:

This example uses a cache to reduce the number of query databases. The reason why the cache is selected is because the cache allows you to set the timeout value. However, if you use a session state, you can reduce the test process because ASP.NET can ensure that users only access their own sessions. Be careful when using such code to ensure that you do not use the wrong body to raise threads running the user request. See the next topic for implementation examples of the GetPrincipal method.

How to build GenericPrincipal using SQL Server

The following example shows a simple database scheme that can be used to import genericprincipal with roles. Run the following code to create a Userroles table:

The subsequent GetPrincipal method has an Iidentity parameter to provide identification information to GenericPrincipal. This code uses the identifier name to find roles in the Userroles table to import the role into the IPrincipal object.

Note that the code passes the identifier as a string to the GenericIdentity constructor without transferring using the IIDENTITY parameter. Pass the identification name as a string so that the code can be used in conjunction with any type of authentication.

The code also passes another string to the GenericIdentity constructor, indicating the original authentication type.

For code examples that call the getPrincipal method, see How to change Principal in the ASP.NET application in the appendix.

How to use System.EnterpriseServices role-based COM security settings

The .NET application uses COM to provide role-based security settings, check the role member relationship with one of the following two methods: manual check or declarative check.

Execute manual inspection or declarative access check

In the code, specify ApplicationAccessControlattribute in the program level, use the AccessCheckSlevel property to set the authorization level. Perform application-level and component-level checks using the AccessChecksLevelOption.ApplicationComponent value. For the corresponding class AppAMPONENTACCESSCONTROLATRIBUTE, enable access checks for components that need to role-based security settings. A class that requires the requirements based on the role check from the servicedcomponent. Using SecurityRoleattribute in assemblies, classes, interfaces, or method levels to add a needed role to your application.

Note: Steps 1, 3 and 4 do not need to be implemented in your code, which can be done in the Component Service Management Console.

Complete the configuration of component service applications

At least to configure authentication in the call level, otherwise, the interceptor cannot access the caller's information. Assign the user allocated the corresponding role.

Note: To make your application work normally, you may need to add a few steps, such as install the assembly in the global program cache. These steps are related to the deployment of the application, and this guide is not introduced. For more information on installing component service applications, see COM Integration: How .Net Enterprise Services CAN Help You Build Distributed Applications in MSDN MAGAZINE.

Perform manual COM role check

Manual role check Depending on whether security can call the context object in the application code. If the security of the component service application is enabled, the context object is available.

When checking the COM role member relationship, use the following technique:

Call the ISCALLERINROLE method of the SecurityCallContext object, check if the user belongs to a certain role. As a preventive measures, the verification has enabled security settings before checking the role member relationship. If security settings are not enabled, the result of calling iscallerinrole is always true. The following code shows how to test security and check the role member relationship.

Create complex checks by using multiple IF statements containing standard syntax (such as logical AND [&&] and logic or [||]). The following code is such a test statement.

Create a constant in the application, or retrieve the user role from an external source (such as a database). Use the SecurityCallContext.currentCall.ORIGINALCALLER attribute to access user information. This property returns a SecurityIdentity object, as shown in the following code.

Perform a declarative COM role check

Declared check Enable users belonging to a specific role to activate the component and call any public method. This type of role check is similar to the grade specified based on role. NET security properties. Specify the role of the class with SecurityRoleattribute, as shown in the following example.

Perform a declarative check until the method level

The steps required to perform a declarative check for methods are more than the level check:

Implement the interface. The SECUREMETHODATTRIBUTE is included in the class or method level. This property is responsible for configuring role security settings in the method level when you install an application to COM . To make all methods, all methods are protected or manually using the management utility to protect all methods, specify this property at the level level. To connect the method link to the role, use SECURITYROLEATITRIBUTE in the method implementation. Manually add users to the MARSHALER role in the Component Service Management Console. When the application is installed into COM , COM will automatically create this role to manage the client and the unmanaged client to call secure methods.

The following code demonstrates these steps.

Feedback and support

If you have any questions, comments, and suggestions, send it via email to devfdbck@microsoft.com. Application Blocks for .NET Components and Guides are intended to assist in developing .NET distributed applications. Example code and guides are provided as it is. Although this product has been tested and considered a reliable assembly, we are not supported as traditional Microsoft products. We also have created a newsgroup that can help you use the Application Blocks for .NET component and guide. You can consult your colleagues, colleagues, and Microsoft support from the Journalic Group's Open Forum. Others can benefit from your questions and comments, our development team will view the newsgroup daily: News Group: Web readers http://msdn.microsoft.com/newsgroups/loadframes.asp?icp=msdn&slcid=us&newsgroup = Microsoft.public.dotNet.Distributed_apps: NNTP reader news: //msnews.microsoft.com/Microsoft.public.dotNet.distribute_apps (English) partner

Thanks to the following for your participation in writing and proofreading experts: Erik Olson, Dave McPherson, Riyaz Pishori, Srinath Vasireddy, Abhishek Bhattacharya (Sapient), Dimitris Georgakopoulos (Sapient), Chris Brooks, Ross Cockburn, Kenny Jones, Angela Crocker, Andy Olson , Lance Hendrix, Mark White, Steve Busby, UNMESH Redkar, JD Meier, and Diego Gonzalez.

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

New Post(0)