Design Patterns-engineering implementation and expansion based on C # security design pattern Series 4 role patterns (role pattern)

Source: Internet
Author: User

Role

Role Mode

Vision Wang)

2009-02-16

Category

Information Security structural mode

Motivation, problems, and Influencing Factors

I believe that you and I often need to learn various rules and regulations from the process of entering the nursery, going to school, and working for more than 20 years, unlike the content of praise/criticism in notices, these rules and regulations are often not for individuals.

Of course, you may jump out and say, "How come? Our company's rules say that reimbursement exceeds 2000.Travel expenses of RMB must go through XThe total approval is acceptable .", If this is the case, there is no way, and we should follow it.

Let's take a look at two examples to check your memories:

Rules

All undergraduates can borrow up to 3 books each time, and 1 humanities book can be borrowed at most on the second floor.

Notification

Zhang San, a 08-level undergraduate in computer science, is included in the data structure examination this semester.

After confirmation by the Academic Affairs Office, the student's score for this test is invalid, and a severe warning is given to the student for further study.

The preceding two examples show that the former is the definition of a rule, and the latter is an instance of another rule. For our applications, our main goal in the development stage is to express various rulesCode(Or similar mechanism), and then the user selects different rules in the specific context during execution.

Taking authorization rules as an example, let's review our previous project experience. permission management for multiple users in a project is often not simple, but typical business systems are often used as the example above, his business rules are usually set based on the positions in the Organization and organization. As an individual, a person flows between different positions through growth and completes different jobs in different positions. Through analysis, we can easily find that if a third-party object is introduced between the "user-operation function" of the original direct link, the impact of the above changes may be effectively isolated. It can package both a bundle of functions and a batch of users, however, in any case, we define a goal-to abstract a group of contents with similar abstract features for the second time.

Solution

The typical role mode solution is abstracted as follows:

"Create a series of objects named 'Role 'and use it to abstract the access permissions of a group of users ".

The difference between direct authorization and traditional authorization is as follows:

Figure 04-01: Authorization structure diagram before and after role is introduced

Scenario for handling larger and more standardized enterprise environmental role models

The transformation of the processing method mentioned above is the main goal of role (s) pattern. Its most common application scenario is authorization. However, for some large projects and super-large projects, if the enterprise's business management system is clear, the job definition is clear, and the project functions are numerous, such a layer of role may not be enough. For example:

L enterprise organizations have layer-4 or layer-5 relationships even at regional headquarters, making the level of personnel positions more complex;

L although there are only 1000 people in regional institutions, the setting of work institutions and Department functions is complicated because they are white-collar personnel;

L The project is a relatively large ERP with more than 14000 functional interfaces;

L The authorized person is the department supervisor, but only two or three persons are actually authorized;

· Communication Between personnel departments is common;

I believe that in the face of such a situation, if we only make a layer of abstraction, we may not be able to authorize the staff to be too busy, then we may wish to make a layer-2 and layer-3 abstraction as needed. For example, the following is a solution:

L The role for "packaging" personnel is called a position, and there are different positions at the same organization level. For example, the organization is the "Development Department" and has the following positions:

N assistant Development Engineer

N Development Engineer

N senior Development Engineer

N designer

N architect

N Department Deputy Manager

N Department Manager

N development director

N...

L The role of the "package" function is called a permission. For example, the project approval permission includes the following features:

N browser requirement analysis book

N browse user habits survey report

N project financial budget registration, modification and report

N...

In this way, more than 14000 features may be merged into seven or eight permissions, and more than 1000 members may be merged into more than 40 positions, reducing the workload by 1 or 2.

Figure 04-02: Application Scenario of multi-layer role mode

More interference-dimension authorization measures

The above is actually just "regular" authorization, but in reality, authorization is often subject to interference from multiple dimensions at the same time. I believe you have a lot of experience with authorization, apart from the simple "user-role-function", we may face many problems:

L authorization is often associated with the territory. With the internationalization and regional characteristics, authorization often requires a dimension-"jurisdiction", that is, you can approve the document, but where can I approve the local and target locations of a document?

L In addition, authorization is often associated with business data. For example, you can approve reimbursement, but can you approve a list with an amount more than 20 thousand yuan? Even if you can define a "large amount of reimbursement for approval" role, is that enough? After all, we may feel that 20 thousand euro yuan is a large amount five days later. Do you need to define another role?

L is there any anti-operation for authorization? For example, although the "cashier assistant" can do some work, whether or not you want to define another role for a new employee who may temporarily "card" off some features, or add a reverse operation in the authorization direction;

L I believe that you have an understanding of the role of a "secretary". What a secretary can do is not only her own permissions, but also her/her ability to act as a proxy for high-level work, but does our senior management like her or their own account/password? Or in some cases, just share some of your "in-shard" functions to her/him. Here we will discuss how to manage such content with a "delegate" relationship;

L how to enable authorized personnel at different levels of an enterprise to view their authorized organizations in a simpler "View. For example, there are many financial departments, including headquarters, regional headquarters, and branches. However, a batch of functions are developed for finance. When authorizing them, they can only see their own domain scope, you do not need to see other departments;

· Communication Between personnel departments is common, and the entire department is often changed or abolished. How to allow authorized personnel to quickly complete similar "batch" authorization;

L is there an absolute vertical leading role between institutions, for example, review and approval? Can the Headquarters personnel directly Approve each ticket of the regional headquarters?

L... ...

To be honest, although there are many ways to solve any problem in a specific project, it is not easy. The main reason is that we should not only provide functions, but also try to avoid the passive situation of "holding a hair and moving the whole body. Refer to the solutions we mentioned at the beginning of this series:

L weaving multi-layer AOP design;

L The multi-level bridge model is used as described in the classical section of "Design Model-engineering implementation and expansion based on C #" gof23;

The logic of the AOP method is as follows:

Figure 04-03: Use AOP to implement a role model with multiple changing dimensions

Figure 04-04: multi-level bridge mode is used to implement the application scenario of the role mode with multiple changing dimensions.

Example

Next, let's restore the initial state of the role mode and look at a specific custom example:

Implementation

Abstract Interface

C #

/// Basic interface of the authorization system

Public interface isecurityobject

{

String name {Get ;}

}

/// Function

Public interface ifunction: isecurityobject

{

}

/// Role

Public interface irole: isecurityobject

{

Ienumerable <ifunction> functions {Get; set ;}

/// Configuration

Void config (ienumerable <ifunction> functions );

}

/// Account

Public interface iaccount: isecurityobject

{

Ienumerable <irole> roles {Get ;}

/// Authorization check

Bool isinrole (string rolename );

/// Authorization check

Bool couldoperatefunction (string functionname );

/// Authorization (forward)

Void grant (irole role );

/// Authorization (reverse)

Void revoke (irole role );

}

Sample object type

C #

Class securityobjectmock: isecurityobject

{

Public string name {Get; set ;}

}

Class functionmock: securityobjectmock, ifunction {}

Class rolemock: securityobjectmock, irole

{

Ienumerable <ifunction> functions;

Public ienumerable <ifunction> Functions

{

Get {return this. functions ;}

Set {This. Functions = value ;}

}

Public void config (ienumerable <ifunction> Functions)

{

This. Functions = functions;

}

}

Class accountmock: securityobjectmock, iaccount

{

Ilist <irole> roles = new list <irole> ();

Public ienumerable <irole> roles {get {return roles ;}}

Public bool isinrole (string rolename)

{

If (string. isnullorempty (rolename ))

Throw new argumentnullexception ("rolename ");

Return

(From role in this. Roles

Where string. Equals (role. Name, rolename)

Select role)

. Count ()> 0? True: false;

}

Public bool couldoperatefunction (string functionname)

{

If (string. isnullorempty (functionname ))

Throw new argumentnullexception ("functionname ");

Return

(From role in this. Roles

From func in role. Functions

Where string. Equals (func. Name, functionname)

Select func)

. Count ()> 0? True: false;

}

Public void grant (irole role)

{

If (role = NULL) throw new argumentnullexception ("role ");

Roles. Add (role );

}

Public void revoke (irole role)

{

If (role = NULL) throw new argumentnullexception ("role ");

Roles. Remove (role );

}

}

Unit Test

C #

[Testmethod]

Public void testauthorizationwithsimplerole ()

{

// Configure the authorization system environment

Irole role1 = new rolemock ()

{

Name = "",

Functions = new list <ifunction> (){

New functionmock () {name = "A1 "},

New functionmock () {name = "A2 "},

New functionmock () {name = "A3 "}

}

};

Irole role2 = new rolemock ()

{

Name = "B ",

Functions = new list <ifunction> (){

New functionmock () {name = "B1 "},

New functionmock () {name = "B2 "}

}

};

// Instantiate the user

Iaccount account = new accountmock ();

// User authorization and permission check

Account. Grant (role1 );

Account. Grant (role2 );

Assert. istrue (account. isinrole (""));

Assert. istrue (account. isinrole ("B "));

Assert. istrue (account. couldoperatefunction ("A2 "));

Assert. istrue (account. couldoperatefunction ("B2 "));

// Adjust authorization and check permissions

Account. revoke (role1 );

Assert. isfalse (account. isinrole (""));

Assert. istrue (account. isinrole ("B "));

Assert. isfalse (account. couldoperatefunction ("A2 "));

Assert. istrue (account. couldoperatefunction ("B1 "));

Assert. istrue (account. couldoperatefunction ("B2 "));

}

Result Analysis

As shown in the preceding example, if "role" and "function" are generalized to character passing names, it is not complicated to implement a custom authorization check function using existing development methods.

However, in the preceding example, ifunction, irole, and iaccount abstract more complex behaviors, such as focusing on authorization subjects, authorization objects, and authorization context, with the role model as an object-oriented system, more flexibility can be granted to the system, especially compared to the solution that uses "simple database + SQL/stored procedure", because of any entity type, it may include more information and control than a name.

Related Mode

As shown above, if the role model is not for the classic design, it is about "packaging" of functions, but about "packaging" of user subjects ", therefore, the combined mode and iterator mode are often used to provide users with simpler authorization functions, such: if you want to grant the "view company annual report" function to all users of a regional center and its subordinate units, you can directly grant related functions to this region, personnel at all levels can perform operations on this function based on the combination and iteration process, without having to authorize the Administrator to grant permissions to each position at any time;

In addition, in some cases, our authorization may not always target roles. As we mentioned at the beginning of this series, there may also be the need for identity based security or identity based security as a supplementary mechanism, at this time, we also need to fully combine the characteristics of the combination mode and iterator mode to solve the issue of authorization at different levels.

If you have browsed design patterns before --Based on C #Engineering implementation and expansion of gof23The introduction of the classic part, I believe that you have clearly felt the characteristics of the combination mode while reading the examples above, while the iterator usesIn fact, the above example adds an isecurityobjectWe also reserve a retreat for the situation discussed here.

As mentioned above, we may also often use the bridge model to solve the situation of multi-dimensional authorization changes and the impact of control factors;

In a specific project, when designing a security mechanism, the checkpoint mode in the previous chapter is often used to implement business authorization and block the "illegal attempt" process as much as possible.

Industry Cases

Windows is a very typical role based security + identity based security system;

QQ group, MSN group, and Gtalk group are typical examples of extending the role mode and implementing group interaction based on typical C2C im tools.

 

More attention:

Design Patterns-engineering implementation and expansion based on C # security design pattern Series 1 public key system and distributed environment requirements

Design Pattern-engineering implementation and expansion based on C # security design pattern Series 3 checkpoint pattern (check point)

Bookmarks on design patterns-engineering implementation and expansion based on C #

On the cover of design patterns-engineering implementation and expansion based on C #

About Design Patterns-implementation and expansion of C #-based engineering, e-books and sample code release, and the beginning of Internet subscription

Pricing modification of design model-C #-based engineering implementation and expansion

"My first planning practices"

My first planning practice-the door to initial directory Analysis

Help you create flexible, scalable, and easy-to-maintain software entities

"Wang Xiang-Design Mode C # engineering implementation" online lecture material download

Expression Pattern of Design Pattern

For more information about "entrepreneurship and promotion", see "getting out of software Workshop".

For more information about "job search and interview", see the beauty of programming-Microsoft technical interview experience.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.