Role-based security in the .NET framework is gradually rising within a quite period of time in the past, and the proportion of information crimes is gradually increased. The US Federal Investigation, computer security organization found 85% of corporate safety of 85% of enterprises in the 2001 research investigation. The property loss reports submitted after these companies were investigated, with a total loss of 300 million US dollars, an increase of 42% compared to 2000 million $ 200,000. It can be clearly seen that the number of hours of computers and information crimes is increasing, and the damage caused by it is increasingly, and the means of crime is increasingly rich, and the enterprise security personnel will prevent it. Therefore, companies must have actions to protect valuable information assets. Naturally, safety is increasingly incorporated in the current program development. Traditional security models provide isolation and access control to the mechanism of users and user groups. This means that the user can run all code, or it cannot be run. And this is now the safety model taken by most operating systems, even if this mechanism is now very effective, we can find that the assumption that this mechanism exists is that all code has the same trust. When all the code is from you or your system administrator, then this assumption is effective. But now most computers have been connected to the Internet, this kind of "all" or "all don't do" is not so good. The .NET framework provides a comprehensive security system enough to cope with most of the current security issues. The traditional model is provided in the .NET framework, but is a security model that is customized by the developer, called Role-based Security. The most important concept based on role is authorization (Identity). Based on the role, it is simple to say that the purpose of program security is to prevent uncomfortable people or procedures cannot do things that administrators and developers don't allow. The traditional security mechanism mentioned earlier focuses on controlling the permissions of the user, limiting the user's operation by verifying the user's identity, so that a particular user can access the resources, in the past, Windows and Both the two most successful operating systems in Unix have taken this safety mechanism. Before discussing .NET security programming, we will first look at the security model provided by the .NET platform, only in-depth understanding of the security model, we can use the platform to provide better security guarantees (hereinafter discussed The operating system is dominated by Windows 2000 and Windows XP). The security model of .NET is in the upper layer of the system's security model, and it is good to combine with some server programs (of course, these products are only limited to Microsoft's own products, such as SQL Server and Internet Information Services (IIS)). . Because .NET is different from the hierarchy of the operating system, the security of the .NET program depends on how such factors: .Net security is configured, how the program component is written, and some by Windows, network settings or The security features set by other programs. The following figure illustrates how the .NET security model works on Windows security subsystem. Administrators use the management console Snap-Ins to set up user accounts and set security policies. At the same time, administrators are also responsible for managing .NET security configuration. When the user logs in the operating system and runs the .NET managed program, the CLR will verify the user and allow the program to perform some actions, then pass these operations to the operating system's security monitor. However, there is a question that requires special attention, that is, no matter how you use .NET security, resources remain under the protection of operating system levels.
For resource-specific resources, the security permissions of .NET platform are unable to force (in fact, this is also in line with the relationship between .NET and operating system). Let's take a detailed look at several concepts based on role-based security, and how these concepts are used in .NET. Authentication refers to the process of determining the user's identity, and authorization refers to the permissions of the user to access a particular resource after passing the above process. Description Who is a little bit, verifying is "who you are", and authorization Is it "what can you do?" .NET provides Principal and Identity objects to implement these two processes, where role-based security base is established on the Principal object, which encapsulates the current user's information, which contains the user's identity, also contains the role he played. The user identity is indicated by Identity object, which not only contains the specified user identity information (user name or account), but also "how to verify this identity". The Identity object Identity object is an instance of a class that implements the IIDENTITY interface. The IIDENTITY interface consists of three read-only properties: String AuthenticationType {get;} Get the type BOOL ISAUThenticated {get;} to get the Boolean value, this value indicates whether the login user has verified String Name {get;} Get the current user The name. Net implements the following four classes of the interface: 1, genericIdentity is used to represent a general user, which can be used to customize the login verification. 2, Windowsidentity is used to indicate a normal Windows user who has successfully logged in to the Windows system. 3, FormSidentity is used to represent users using Forms authentication in the ASP.NET application. 4. PassportIndentity is used to represent users in applications using Passport. However, pay attention to the PASSPORT SDK can be installed to use this class. Because the most used in the current specific development is the top three, and the FormSIDENTITY class will specifically explain it later, so we will discuss the first two genericidentity class GenericIdentity classes, which is not very simple, it is not any A specific verification protocol is associated. Therefore, it is often used in applications with custom landing mechanisms. For example, a program can prompt users to enter usernames and passwords, then go to custom user databases to query. If the username and password are valid, the program creates a Principal and (corresponding) Identity object based on matching records in the database. The GenericIdentity class has no more things except for the three IIDENTITY interfaces defined. However, the GenericIdentity class provides two constructor. A constructor accepts a string parameter, which specifies the username; another constructor accepts two parameters: the first is a username string, the second is a given verification type string.
Public genericidentity; public genericidentity (String name, string type); Now we don't have more detail issues using the GenericIdentity class, after we will see how you use GenericIndentity objects in an actual program. The WindowsIdentity class acts as a derived class that implements the IIDENTITY interface, and the WindowsIdentity class is mainly used to indicate users who have successfully logged in to Windows. Let's take a look at the constructor, properties, and methods of the Windowsidentity class. In the constructor, you will use the INTPTR type parameters, let's take a look at this data type, the intPtr type is usually used to represent the data type associated with the platform, such as a memory pointer or a handle. In our case, the intPtr parameter is usually used to represent a Win32 handle, and this handle points to an account tag for a 32-bit user (Account token). This tag is typically obtained by calling the unmanaged Win32 API. public WindowsIdentity (IntPtr userToken); public WindowsIdentity (IntPtr userToken, string authType); public WindowsIdentity (IntPtr userToken, string authType, WindowsAccountType acctType); public WindowsIdentity (IntPtr userToken, string authType, WindowsAccountType acctType, bool isAuthenticated); each constructor They have the same intptr parameters, followed by some parameters with other information: Verification Type, Windows account type, and verification status. Note that the WindowsAcCountType parameter must use one of the following enumeration values: Anonymous, Guest, Normal, System. For a reason, the Windowsidentity class also has three readite properties of the Iidentity interface: AuthenticationType, ISAUThenticated, and Name. In addition, the Windowsidentity class has its own unique properties: Isanonymous, ISGUEST, and ISSYSTEM, with these three properties can better determine user accounts. Then come and see the method of the Windowsidentity class. In addition to the way to inherit in the Object class, the WindowsIdentity class has three ways: getanonymous, getcurrent, and impersonate. 1. The getanonymous method returns a WindowsIdentity object that represents an anonymous user. 2. The getCurrent method returns a WindowsIdentity object that represents the current user. 3, the Impersonate method allows you to temporarily simulate a user.
Both the GetAnonymous and getCurrent methods returns a WindowsIdentity object, which is also very simple, we need to pay attention to the Impersonate method, which has two versions: instance version (Instance Version) and static versions. The method of the instance version does not with the parameters, returns a WindowsimPersonationContext object based on the called WindowsIdentity object (Windows IMPERSOTIONContext class represents a Windows user before analog operation); static version requires an intPtr parameter. This simulation operation is useful for server programs, which can reduce the permissions of user accounts used by the client access server to a certain extent. The following is a specific syntax of the above method: public static WindowsIdentity GetAnonymous (); public static WindowsIdentity GetCurrent (); public virtual WindowsImpersonationContext Impersonate (); public static WindowsImpersonationContext Impersonate (IntPtr userToken); Principal Object Principal object classes that implement the IPrincipal interfaces Examples, these objects are used to represent users and include user identity information. System.security.principal namespace includes several types of Principal classes that encapsulate the security environment of the program code running. We will see later to check the username and role to determine if the user identity and the role can make the user to perform some of the sample code of certain specific operations. For each thread is associated with a Principal object. This Principal object includes an IDENTITY object that represents a user running the current thread. We can use the static property of the Thread class CurrentPrincipal to get this Principal object. Let's take a look at the iprincipal interface that only one Identity public property and isinrole public method: 1. Identity property points to a IIDENTITY object associated with the Principal object. 2. Isinrole method requires a string parameter that is a name of a role and returns a Boolean value indicating whether the Principal object belongs to the specified role. Due to the actual development needs, we have more contact with the WindowsPrincipal class. The WindowsPrincipal class will be discussed in detail. Relatively, the genericprincipal class is just a short. GenericPrincipal class genericprincipal class is used to represent a user that is customized, usually used with the GenericIdentity class.
Here is a simple program that illustrates how to use these two classes: // create a GenericIdentity objects IIdentity myGenericIdentity = new GenericIdentity (strUserName, "MyAuthenticationType"); // create a GenericPrincipal objects String [] roles = null; GenericPrincipal myGenericPrincipal = new GenericPrincipal (myGenericIdentity, roles); GenericPrincipal the object // created attached to the current thread Thread.CurrentPrincipal = myGenericPrincipal; Note that in the above example, we can replace the MyAuthenticationType authentication type known as NTLM or Kerberos authentication Authentication. Here is the process of verification: // Get the current thread's principal target IPrincipal principal = Thread.CurrentPrincipal; if {throw new SecurityException (strUserName "NOT PERMITTED to proceed (principal.Identity.Name.Equals (" TrustedUser ")!). / N ");} console.writeline (StruserName " is permitted to proceed./n "); WindowsPrincipal class WindowsPrincipal class As the most frequently encountered a class that implemented the iPrincipal interface in development, the constructor is quite simple: public WindowsPrincipal (WindowsIdentity ntIdentity); the following code shows how to create a WindowsPrincipal object: WindowsIdentity wi = WindowsIdentity.GetCurrent (); WindowsPrincipal wp = new WindowsPrincipal (wi); WindowsPrincipal class should be noted that the following three overloaded IsInRole Method: Public Virtual Bool Isinrole (int); the first load function accepts a complete parameter that represents the RID corresponding to the user group (RID is the Domain-Relative SubauThority ID associated with the domain). RID values are defined in the header file Winnt.h Platform SDK's, Winnt.h included some common users and groups, such as DOMAIN_USER_RID_ADMIN, DOMAIN_USER_RID_GUEST, DOMAIN_GROUP_RID_ADMINS, DOMAIN_GROUP_RID_USERS and DOMAIN_GROUP_RID_GUESTS etc., can ... / Microsoft Visual Studio .NET This file is found in the / VC7 / PlatformSDK / INCLUDE folder.
Public Virtual Bool Isinrole (String); The second load function accepts a string parameter that represents a user group name, such as MyComputer / developer (MachineName / Groupname) represents the west server named MyComputer's WeComputer . However, for the system built-in user group, it cannot be said, such as Administrators, cannot be represented as MyComputer / Administrators, and should be like Builtin / Administrators, but this always feels a bit of a bit, not natural. So we can use the following overload function. Public Virtual Bool Isinrole (WindowsBuiltinrole); The third load function accepts a WindowsBuiltinrole enumeration type parameter, below the value defined in the WindowsBuillTinrole enumeration: 1, Accountoperator - Manage the user account on your computer or domain. 2, administrator - can access computer or domain arbitrarily, BackupopOperator - can perform backup and recovery operations on the file system. 4, Guest- and User, but there are more restrictions. 5, PowerUser- and administrator status, but there are some restrictions. 6, Printoperator - Perform a print operation. 7, replicator - execute file replication in the domain. 8, Systemoperator - Manage Computers. 9. User-users cannot perform hazards or affect the entire system. Permissions objects as two important branches of .NET security, role-based security and code access security are inseparable from an important concept-permission (Permissions). In role-based security, the PrincipalPerMission class is used to check the user identity of the calling thread; and in the code access security, the class derived from the CodeAccessPermission is used to check all threads that perform the current method. Permissions. Permissions objects are permitted or rejected by existing security policies. For code access security (but this does not apply to user rights), the NET CLR provides a stack traversal mechanism to determine if all call stack frames have permissions. It is important to note that if the Permission object is null, then we can treat it and permissionstate.none as equivalent, indicating that no permissions are provided. Permissions are commonly used in the following: 1. Define the permissions required to execute code. 2. The security policy of the system can recognize or reject the permission of the code request. 3. The code is guaranteed by the Demand method (requires) the code it calls has the required permissions. 4, code can also use Assert, Deny or Permitonly method to skip the security stack checking mechanism. In addition, we can also use the group's permissions, we can use a variety of different permission groups in the Permissionset class. Let's first take a look at the most commonly used PrincipalPermission class, as for another commonly used CodeAccessPermission class, will later introduce in the contents of the code access secure.
As one of the three interfaces implemented by the PrincipalPermission class, the iPermission interface has a pivotable role in the PrincipalPerMission class. The iPermission interface provides the following methods: 1. Copy created and returned the same copy of the current permissions. 2, Demand If the contents of the stack do not meet the permissions specified by the permission object, SECURITYEXCEPTION will be triggered at runtime. This method can make the current code will not be utilized by other malicious code. 3, INTERSECT creates and returns a permission, which is the intersection of current permissions and specified permissions. 4. Issubsetof determines if the current permissions are subset of specified permissions. 5, Union creates a permission that is the pane of current permissions and the specified permissions. In the methods listed above, the Demand method is the most commonly used method. The Demand method checks all the calvity of the current method to determine if they have sufficient permission access to access specific resources in a specified manner (usually checking the latest calling method on the calling stack, starting through the full stack traversal To meet safety conditions, but the stack traversal is not necessary, PrincipalPermission.Demand does not make stack traverses), if check failed, the Demand method throws the securityException exception, only without any exception thrown, the Demand method successfully returned . The following figure shows the inheritance level of the iPermission interface: [IMGHTTP: //myArticle.net.com.cn/images/200407/10981312024.gif [/ img] then let us discuss the PrincipalPermission class, here you need to talk about before Principal object, when executing the Demand method at the instance of the PrincipalPerMission class, is actually determined whether the current Principal object matches the given PrincipalPerMission object. If you do not match, you will throw the securityException. In addition, the Demand method can also be used to force the Identity authentication of the Principal object so that it can do not throw an exception and perform normal operation. The following code fragment briefly explain how principalpermission objects: String user1 = "Abbott"; String role1 = "StraightMan"; PrincipalPermission PrincipalPerm1 = new PrincipalPermission (user1, role1); String user2 = "Costello"; String role2 = "FunnyMan "; PrincipalPermission PP = new PrincipalPermission (user2, role2); PrincipalPerM1.Union (PP) .demand (); The above code shows how to use the two PrincipalPerMission objects, after the merge, if the user is the abbott of the Straightman role or The funnyman role Costello, then Demand will successfully return.