Unify the role-based security models for enterprise and application domains with .net

zhaozj2021-02-11  171

Download the code for this article:. RollSec.exe (161KB) SUMMARY Role-based security allows administrators to assign access permissions to users based on the roles they play rather than on their individual identities These privileges can be used to control access to objects and methods, and are easier to identify and maintain than user-based security The .NET Framework provides two role-based security models, which are exposed as two namespaces:. System.Enterprise-Services and System.Security.Permissions.Presented here is a COMPARISON OF THE THEN EACH IS The Right Choice. The Author Also Demonstrates The Process Involved in Setting Up Access Security and Discusses Role Memberships.

ole-based security is by far the most elegant and productive way to provide user authorization and access checks for your application. A role is a category of users who share the same security privileges. When you grant a given role access to an object or a particular method on that object, you grant it access to the members of that role, freeing you from having to assign specific access rights to individual users.Discovering the roles users play in your business domain is part of your application requirement analysis and design, just as factoring components and interfaces is. Using roles instead of particular users means you do not have to change your application when changes occur in real life, such as new users being added, existing users moving between positions, users being promoted, or users leaving THEIR JOBS.MICROSOFTROET Allows Developers To Use role-based security as attributes, freeing the business logic from having to deal with security access checks. in Fact, .Net Offers T wo role-based security models. This article's downloadable sample code contains a handy utility that unifies the two security models, allowing you to get the best of both models without compromising on ease of use or having the components using basic role-based security do anything differently. I've used some advanced and valuable C # programming techniques such as language features and reflection in building this utility.Role-based Security ModelsThe first role-based .NET Security model is part of the vast component-oriented permission and evidence based security Infrastructure Built INTO .NET. IT '

s available in the System.Security.Permissions namespace. To understand this first model, imagine a bank account component that provides methods for opening an account and retrieving the account's balance. As part of the requirements analysis, you discovered that only tellers can open an account, but that both tellers and customers can retrieve the account's balance.To implement this requirement, use the PrincipalPermission attribute, specifying the roles you grant access to and the security action to perform. In this case, the security action specified (SecurityAction.Demand Needs to Verify The Caller's Role Membership During Call Time, Before ALLOWING TOGLO Go THROUGH: Using System.security.Permissions; Public Class BankAccount

{

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

Public long OpenAccount () {...}

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

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

Public long getBalance () {...}

/ * REST OF THE IMPLEMENTATION * /

}

By default, a security role in .NET is a Windows? User group. In my example, only if the caller is a member of the Teller Windows user group will it be allowed to call the OpenAccount method.The second role-based security model is part of .NET Enterprise Services and is defined in the System.EnterpriseServices namespace .NET Enterprise Services are actually the result of integrating COM component services with .NET They offer a wide range of component services essential for any nontrivial application:.. object pooling ; instance management; transactions; concurrency management; security; loosely coupled events; and asynchronous, disconnected calls.In order to implement the same requirement as in the previous example using .NET Enterprise Services, derive the BankAccount class from ServicedComponent (components that use. Net Enterprise Services Are Called Service Components, And Use The SecurityRole Attribute: Using System.EnterpriseServices; Public Class BankAccount: ServicesDComponent

{

[SecurityRole ("teller")]]]]

Public long OpenAccount () {...}

[SECURITYROLE ("Customer")]]

[SecurityRole ("teller")]]]]

Public long getBalance () {...}

/ * REST OF THE IMPLEMENTATION * /

}

An Enterprise Services role is defined in the Enterprise Services Catalog in the application that the serviced component is part of. Typically, you would use the Component Services Explorer (also known as the COM Explorer) to define these roles, but you can also use the SecurityRole Attribute as an assembly attribute to define the: [askEMBLY: SecurityRole ("teller")]

[Assembly: SecurityRole ("Customer")]]

Then use the Component Services Explorer to add users (or user groups) to these roles. Figure 1 shows the Bank App application with the Teller and Customer roles.Figure 1 Teller and Customer RolesComparing the Two ModelsThe two role-based security models complement each other , and neither is superior in all respects. The main drawback of the .NET basic role-based security model is that it can be only as granular as the user groups in the hosting domain. Often you do not have control over your customer's IT department . If you deploy your application in an environment where the user groups are coarse, where the user groups do not map well to actual roles users play in your application, or where the group names are slightly different, then .NET basic role-based security is of little use to you.The Enterprise Services role-based security is in principle unrelated to Windows user groups, allowing you to define roles directly from the application's business domain, even if no corresponding u ser groups exist. Of course, you can associate actual user groups with Enterprise Services roles if such groups exist.On the other hand, .NET basic role-based security offers a rich set of security actions to perform in conjunction with the role membership information . The SecurityAction enumeration provides other values ​​besides SecurityAction.Demand, such as SecurityAction.LinkDemand, to verify role-membership during the JIT compilation link phase instead of on every call. SecurityAction.LinkDemand may be more useful to you if it is always the same Client Calling your Object, And It Will Yield Better Performance In Certain INTENSE CALLING PATTERNS. See Keith Brown's Article

Security in .NET: Enforce Code Access Rights with the Common Language Runtime "(MSDN Magazine, February, 2001) for more information on possible SecurityAction values.Another advantage to the basic security model is that it imposes no restrictions on the base class, unlike Enterprise Services, which requires deriving from ServicedComponent.A typical enterprise application will almost certainly be comprised of both serviced components and regular components. It simply does not make any sense having two security models for the same application with two separate definitions of what roles are and separate allocation of users to those roles.Solution ArchitectureLike most other pieces of the .NET Framework, the security infrastructure is extensible, and you can pretty much plug in your own implementation of any key element of it. in fact, it is surprisingly easy To do so, and you will see THAT PLUGGING IN Your Implementation Takes ONLY TWO or Three Lines of code.in .net, user information, and In Particular User Identity and Role Membership, IS Repented by the iprincipal interface defined in the system.security.principal namespace: public interface iprincipal {

Iidentity Identity {Get;}

Bool isinrole; String Role

}

Every .NET thread has a principal object associated with it You can access the principal object via the thread class's static CurrentPrincipal property, which returns an IPrincipal object:. IPrincipal principal = Thread.CurrentPrincipal;

When the PrincipalPermission attribute needs to verify that the caller is in the specified role, .NET simply retrieves the principal object from the current thread and calls IsInRole. Nothing in the PrincipalPermission attribute implementation pertains to how role membership verification is made.The default implementation of IsInRole, when used with the principal object, looks up the Windows user group named as the role and verifies that the caller is a member of that group The caller is represented by an object that implements the IIdentity interface defined as follows:. public interface IIdentity {

String AuthenticationType {Get;}

Bool isauthenticated {get;}

String name {get;}

}

Every principal object has an identity object associated with it, accessible via the read-only Identity property of the principal object. The caller's user name is accessible via the read-only Name property of the identity object.As you can see, there is complete separation between the PrincipalPermission attribute and the principal object. to unify the two role-based security models, all I needed to do was provide my own custom security principal. I call this custom principal the UnifiedPrincipal. The implementation of IsInRole in UnifiedPrincipal can verify the caller is a member of an Enterprise Services role instead of a Windows group.In fact, UnifiedPrincipal lets you choose the security model to use. you can use Enterprise Services only, Windows groups only, both, or either. Using both means the calling user Must Be a Member of Both An Enterprise Services Role and a matching windows user group. using Either means as long one of the role definitio ns, IsInRole will return true.The UnifiedPrincipal class public members are listed in Figure 2. (See the code download for this article at the link at the top of this article to get the UnifiedSecurity solution that contains the UnifiedPrincipal class library and a test client application) .Using the unified security principal requires adding only one line of code to every app domain for selecting the security model Typically, you would add this line to your application's Main:. static void Main () {

UnifiedPrincipal.SetModel (SecurityRoleModel.Enterprise ";

/ * REST of main () * /

}

But even if you develop a class library, you can call SetModel in your component's code. As you will see later on, there is no harm in calling SetModel multiple times. In addition, neither the client nor the server assemblies need to be part of an Enterprise Services application or contain serviced components.As you know, C # does not support default parameter values. you can simulate them, however, by overloading methods. UnifiedPrincipal has overloaded setModel methods, providing you with four ways of specifying the security model to use and the Enterprise Services application name containing the role. The default model is SecurityRoleModel.EnterpriseServices. That's all you need to know to use UnifiedPrincipal. Now let's see how the UnifiedPrincipal is implemented.Applications and AssembliesThe UnifiedPrincipal has to know the name of the Enterprise Services Application in which to look for the role and the user membership. if the assembly calling setmodel provides an Application NAM e as an argument, then that name is used. But what should UnifiedPrincipal do if no name is provided? In general, when adding an assembly to an Enterprise Services application, you have a number of options for specifing the application name. You can use The assemblyname assembly attribute: [askEMBLY: ApplicationName ("myApp")]]

If no name is provided, .NET uses the assembly name for the application name.Even though the assembly using UnifiedPrincipal may not contain serviced components at all, it makes sense to follow the rules in case it does. When an assembly uses the UnifiedPrincipal's SetModel method without providing an application name, the UnifiedPrincipal will use reflection to look for the ApplicationName attribute in the calling assembly. If none is found, it will use the calling assembly name for the application name. UnifiedPrincipal has a helper method called GetAppNameFromAssembly, shown in Figure 3.GetAppNameFromAssembly accepts an assembly object representing the calling assembly as an argument. It then retrieves an array of attributes of type ApplicationName associated with that assembly. A given assembly can have at most one such attribute, so the array size must be zero or One. You can discover the array size using the length of any c # array object. if the array size is zero (no at tribute available), then the assembly name is returned using the GetName method of the assembly object. Note that GetName does not return a string, but a strongly typed AssemblyName object. You can get the human-readable assembly name by accessing the AssemblyName's Name Property.if the assembly does contain an assemblyname attribute, the attribute '

s Value property is the requested application name. Simple enough. But then how would UnifiedPrincipal get an object representing the calling assembly in the first place? Luckily, the Assembly type provides the static method GetCallingAssembly, which returns an assembly object representing the calling assembly immediately . up the call chain So the setModel versions that do not accept the application name as an argument use GetCallingAssembly to get the calling assembly object, and then call GetAppNameFromAssembly: static public void setModel (SecurityRoleModel model) {

AskEMBLY CALLINGASSEMBLY = ask.GETCALLINGASSEMBLY ();

String Appname = getAppnameFromassembly (CallingAssembly);

SetModel (AppName, Model);

}

Installing a Custom Security PrincipalI wanted to prevent the user from instantiating a UnifiedPrincipal object directly. UnifiedPrincipal is mostly for .NET use, and the stability of all the objects using the PrincipalPermission attribute depends on it. It is common practice in .NET in similar cases to provide only public static methods, and have the static methods internally use a protected or private constructor to create the object This is exactly what the fully parameterized setModel method does:. static public void setModel (string appName, SecurityRoleModel model)

{

UnifiedPrincipal Principal = New UnifiedPrincipal (Model);

Principal.appname = appname;

}

SetModel creates a new UnifiedPrincipal object whose constructor does the actual work of installing itself as a custom principal. The constructor code is shown in Figure 4.Before you can do anything meaningful with .NET role-based security, you have to set your current app domain principal policy. The available options are no principal (not useful for you because you want to install and use a principal), unauthenticated principal (not much use for role-based security in general), and WindowsPrincipal. This is exactly what the first TWO LINES of the constructor do: appdomain currentdomain = thread.getdomain (); currentdomain.setprincipalpolicy (PrincipalPolicy.WindowsPrincipal);

You get your current app domain using the Thread class's GetDomain static property. Next, the constructor checks the constructor argument spade he security model. If it's SecurityRoleModel.WindowsGroups, then there is nothing to unify, and the default .NET behavior is just fine, so the constructor simply exits.If a unified model is requested (Enterprise Services, both, or either), then the constructor saves the requested model value as well as the current principal and identity objects (you will see why shortly) .To actually install A Custom Principal, All You Have to Do Is Assign The CurrentPrincipal Property of The Current Thread: thread.currentprincipal = this

In essence you are finished. You still have to repeat the assignment on every new thread created in this application domain in order to override the .NET default principal. Yet again, provides an easy remedy via .NET the application domain object's SetThreadPrincipal method. When you call this method, you provide .NET with a new default principal to use for all new threads.You can only call SetThreadPrincipal once per application domain, and you must verify that you called it only once. Therefore, the constructor compares the type of the default principal with UnifiedPrincipal using the C # is operator, and proceeds to call SetThreadPrincipal only if the type of the default principal is not UnifiedPrincipal: if (m_DefaultPrincipal is UnifiedPrincipal == false) {

CurrentDomain.SetthreadPrincipal (this);

}

Role Membership LookupUnifiedPrincipal must provide the IPrincipal's IsInRole method To implement IsInRole, UnifiedPrincipal has two helper methods:.. IsInWindowsGroup and IsInEnterpriseServicesRole UnifiedPrincipal uses these helper methods according to the value of the requested security model, passed as a constructor argument, and saved in m_Model. figure 5 shows the implementation of IsInRole.Implementing IsInWindowsGroup is trivial once you realize that this is exactly the default .NET principal behaviorprotected bool IsInWindowsGroup (string group)

{

Return m_defaultprincipal.isinrole (group);

}

and this is why the constructor saved the default principal.IsInEnterpriseServicesRole is where UnifiedPrincipal has to find the role in the Enterprise Services Catalog and look up the user in that role. The Enterprise Services Catalog provides a generic iteration programming model. Folders in the Component Services Explorer are represented by Catalog Collections. Individual items in a Collection are represented by Catalog Objects. All Catalog Collections provide the ICatalogCollection interface, which allows you to iterate over individual Catalog Objects. And all Catalog Objects provide the ICatalogObject interface, which allows you to access named properties.The Catalog itself is accessible by creating an object of type COMAdminCatalog, which provides the ICOMAdminCatalog interface and serves as the root of the Catalog. The Catalog type definitions are not available out-of-the-box in .NET. You must Import the COM 1.0 Admin Type Library Useing The CoM Tab of The Add Reference Dialog B ox. Once imported, the Catalog types are available under the COMAdmin namespace.There are quite a few details to master when programming against the Catalog. In a nutshell, by using ICOMAdminCatalog, UnifiedPrincipal gains access to the Applications Collection where it scans the items ( application objects) searching for a match against the application name. Once it finds the application, it then accesses its Roles Collection.The Roles Collection has one Catalog Object per role. UnifiedPrincipal scans the Roles Collection searching for the specified role. Once found, it Accesses the role '

s UsersInRole Collection. UsersInRole contains the users associated with that role as shown in Figure 6.Figure 6 Navigating the Component Services CatalogRecall that the UnifiedSecurity constructor cached the existing IIdentity object. This identity object provides the Name property. All UnifiedPrincipal has to do is compare each user Catalog Object in UsersInRole with the identity's name. If a match is found, then the caller is a member of the specified role.Figure 7 shows the implementation of IsInEnterpriseServicesRole with error handling removed for clarity.Wrap-upYou've seen how easy it is to extend a core building block of .NET and plug a custom block with literally one line of code. Accomplishing the same functionality in Windows would have required serious programming, not to mention considerable in-depth security expertise. This is no surprise because Windows Was Never Meant For Su Su, DXTENED with THILE IN MIND.Even Though The Implementation Detail s of this custom principal are specific to the problem at hand (unifying .NET role-based security models), learning how to provide a custom security principal is useful in a number of other scenarios. Imagine an ASP.NET application that maintains a user / password / role database. You can write a custom principal to look up role membership in the database and still use the PrincipalPermission attribute. in general, writing a custom principal is an important technique for using the same business components code with different authorization implementations.

For related articles see: Security in .NET: Enforce Code Access Rights with the Common Language RuntimeSecurity Briefs: Managed Security Context in ASP.NEThttp: //www.discuss.develop.com/dotnet.html For background information see: Version 1 Security Changes for the Microsoft .NET FrameworkJuval Lowy is a seasoned software architect providing consulting and training on .NET design and .NET migration. This article contains adaptations from his book COM and .NET Component Services (O'Reilly, 2001). Contact Juval at http://www.idesign.net.

Figure 2 UnifiedPrincipal Public Members Public Enum SecurityRoleModel

{

WindowsGroups,

EnterpriseServices,

Either,

Both

}

Public Class UnifiedPrincipal: iPrincipal

{

Static public void setmodel () {}

Static Public Void SetModel (String Appname) {}

STATIC PUBLIC VOID SETMODEL (SECURITYROLEMODEL MODEL) {}

Static Public Void SetModel (STRING APPNAME, SECURITYROLEMODEL MODEL) {}

// iprincipal methods:

Public Iidentity Identity {Get;}

Public Bool Isinrole; String Role

/ * REST OF Class Definition: protected methods and members * /

}

Figure 3 The getAppnameFromassembly method public static string getAppnameFromassembly (askASEMBLY Assembly)

{

TYPE AttributeType = TypeOf (ApplicationNameAttribute);

Object [] objarray = ask.getcustomattributes (attributeType, true);

// One ApplicationName Attribute Is Allowed At Most

Debug.Assert (objarray.length == 1 || Objarray.Length == 0);

IF (Objarray.Length == 0)

{

// in the Absence of ApplicationName Attribute, Assembly Name IS

// @

AskEMBLYNAMESSEMBLYNAME = askEMBLY.GETNAME ();

Return asmblyname.name;

}

ApplicationNameAttribute AppNameAttribute;

AppnameAttribute = (ApplicationNameAttribute) Objarray [0]; Return AppNameAttribute.Value;

}

Figure 4 Installing The Custom Principal PUBLIC CLASS UNIFIEDPRINCIPAL: IPRINCIPAL

{

protected string m_appname;

Protected Iidentity M_Identity;

Protected ibrincipal m_defaultprincipal;

Protected securityRolemodel M_Model;

Protected unifiedprincipal (SecurityRolemodel Model)

{

Appdomain currentdomain = thread.getdomain ();

CurrentDomain.setPrincipalPolicy (PrincipalPolicy.WindowsPrincipal);

IF (model == securityrolemodel.windowsgroups)

{

Return; // don't do anything, default is fine

}

M_Model = Model;

M_Appname = ""

// Save Old Principal

m_defaultprincipal = thread.currentprincipal;

// USE Current Identity

m_idententity = thread.currentprincipal.identity;

// make Us the Principal for this Thread

Thread.currentprincipal = this;

// Make Sure All Future Threads in this app domain use this

// Principal But Because Default Principal Cannot Be Set Twice:

IF (m_defaultprincipal is unifiedprincipal == false)

{

CurrentDomain.SetthreadPrincipal (this);

}

}

/ * REST OF THE CLASS DEFINITION * /

}

Figure 5 Implementing Isinrole Public Bool Isinrole (String Role)

{

Switch (m_model)

{

Case SecurityRoleModel.either:

{

Return isinWindowsGroup (role) || isinenterprisesRVicesRole (role);

}

Case SecurityRoleModel.EnterpriseServices:

{

Return IsnenterpriseServicesRole (Role);

}

Case SecurityRolemodel.both:

{

Return isinwindowsGroup (role) && isinenterprisesRiCESROLE (Role);

}

DEFAULT:

{

Debug.assert (false);

Return False;

}

}

}

Figure 7 Implementing isinenterprisesRVicesRole Using Comadmin;

Public Class UnifiedPrincipal: iPrincipal

{

protected string m_appname; protected iidity m_identity;

Protected securityRolemodel M_Model;

Protected Bool IsnenterpriseServicesRole (String Role)

{

BOOL INROLE = false;

String Username = m_idententity.name;

// Find Application

IComAdmincatalog catalog;

ICATALOGCOLLECTION ApplicationCollection;

IcatalogObject Application = NULL;

int ApplicationCount;

INT appindex = 0;

Catalog = (iComAdmincatalog) New Comadmincatalog ();

ApplicationCollection =

(ICATALOGCOLLECTION) CATALOG.GETCOLLECTION ("Applications");

// read the information from the catalog

ApplicationCollection.Populate ();

ApplicationCount = ApplicationCollection.count;

String TempName = ""

While (TempName! = M_Appname && AppIndex

{

// Get The Current Application

Application = (iCATALOBJECT) ApplicationCollection.get_Item

(APPINDEX );

TempName = Application.name.toString ();

}

Object AppKey = Application.Key;

// Get Roles Collection

ICATALOGCOLLECTION ROLECOLECTION;

Rolecollection =

ApplicationCollection.getCollection ("Roles", AppKey);

Rolecollection.Populate ();

INT roleIndex = 0;

While (INROLE == false && roleIndex

{

// Get Individual Role

IcatalogObject roleobj;

RoleObj = (iCATALOBJECT) Rolecollection.get_Item (roleIndex);

IF (roleobj.name.tostring ()! = role)

{

RoleIndex ;

CONTINUE;

}

// role name match. Get users collection, And Check Each User

Object rolekey = roleobj.key;

IcatalogCollection UserCollection;

UserCollection = (iCATALOGCOLLECTION) Rolecollection.getCollection

("UserSinrole", RoleKey;

UserCollection.Populate (); int userindex = 0;

While (INROLE == False && userindex

{

// Get Individual User Object

ICATALOBJECT User;

User = (iCATALOBJECT) UserCollection.get_Item (UserIndex);

// for Each User, Get Users Name, And Compare

IF (username == user.name.tostring ())

{

INROLE = True;

Break;

}

// User in a role can actually be a user group. Check Membership

// By Using Generic Principal, That Considers User Group AS

// "role"

INROLE = ISINWINDOWSGROUP (User.Name.tostring ());

UserIndex ;

}

RoleIndex ;

}

Return INROLE;

}

/ * REST OF THE CLASS DEFINITION * /

}

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

New Post(0)