[. Net role-based security verification] 4: ASP. NET 2.0 membership and role management authorization

Source: Internet
Author: User

Strictly speaking, ASP. NET 2.0 does not have much to do with membership, role management authorization, and. Net role security. Microsoft has done some work for us that we originally needed.

The "Provider Model" used in these two new technologies is worth learning, because the IOC concept is very similar.

Member qualifications

Membership provides common user management functions, such as registration, login, password retrieval, and other visual controls, we almost don't have to write additional code to work. Is that true? Memebershipuser has few attributes and is obviously not suitable for commercial applications. The registration and login controls lack verification codes and lack security ;...... Of course, we can also use custom verification and providers, but it is better to Develop a set by referring to the "Provider Model". After all, independent passport is what we need, not to mention integration with existing systems. In short, Asp. NET provides this new function, which is boring and a pity. The use of membership and role management is not the focus of this Article. For details, refer to the msdn documentation.

Membership is composed of membership, membershipuser, and membershipprovider. Membership is a static class that provides users with a large number of user-related operation methods. membershipuser is a user entity class, in addition to user attributes, there are some user operation methods. membershipprovider is the basic abstract class of the provider, which standardizes the interfaces of the provider.

Let's analyze the membership code (partial Code) to see how to obtain the real target provider object. In fact, the process is also very simple. Read the configuration to get the type information, and then use reflection to create the target provider object instance.

System. system. Web. Security. Membership

// Start with the validateuser method.
Public static bool validateuser (string username, string password)
{
// Obtain the provider object through the provider attribute
Return membership. provider. validateuser (username, password );
}

Public static membershipprovider provider
{
Get
{
// It should be obtained through the initialize () method and assigned to the s_provider variable.
Membership. initialize ();
Return membership. s_provider;
}
}

Private Static void initialize ()
{
// Read the configuration information from the configuration file
Runtimeconfig config1 = runtimeconfig. getappconfig ();
Membershipsection Section1 = config1.membership;

Membership. s_providers = new membershipprovidercollection ();

// Use the providershelper. instantiateproviders method to read the settings from the configuration information.
Providershelper. instantiateproviders (section1.providers, membership. s_providers, typeof (membershipprovider ));

// Assign the default provider object to the s_provider variable.
Membership. s_provider = membership. s_providers [section1.defaprovider provider];
Membership. s_initialized = true;
}

Public static void providershelper. instantiateproviders (providersettingscollection configproviders, providercollection providers, type providertype)
{
// Read the configuration information cyclically and create the provider object.
Foreach (providersettings settings1 in configproviders)
{
Providers. Add (providershelper. instantiateprovider (settings1, providertype ));
}
}

Public static providerbase providershelper. instantiateprovider (providersettings, type providertype)
{
Providerbase base1 = NULL;
Try
{
// Call httpruntime. createpublicinstance to create the provider object.
Base1 = (providerbase) httpruntime. createpublicinstance (type1 );
}
Catch (exception exception1)
{
}
Return base1;
}

Internal static object httpruntime. createpublicinstance (type)
{
// Use reflection to create an object
Return activator. createinstance (type );
}

Next we will analyze the source code of the login control, and we will find that it only automatically calls membership and membershipprovider internally for operations.

System. Web. UI. webcontrols. Login

Private void attemptlogin ()
{
If (this. Page = NULL) | this. Page. isvalid)
{
Logincanceleventargs args1 = new logincanceleventargs ();
This. onloggingin (args1 );
If (! Args1.cancel)
{
Authenticateeventargs args2 = new authenticateeventargs ();

// Call the core code
This. onauthenticate (args2 );

// What do you see? Standard Authentication code. For more information, see the previous blog.
If (args2.authenticated)
{
Formsauthentication. setauthcookie (this. usernameinternal, this. remembermeset );
This. onloggedin (eventargs. Empty );
This. Page. response. Redirect (this. getredirecturl (), false );
}
Else
{
This. onloginerror (eventargs. Empty );
If (this. failureaction = loginfailureaction. redirecttologinpage)
{
Formsauthentication. redirecttologinpage ("loginfailure = 1 ");
}
Itextcontrol control1 = (itextcontrol) This. templatecontainer. failuretextlabel;
If (control1! = NULL)
{
Control1.text = This. failuretext;
}
}
}
}
}

Protected virtual void onauthenticate (authenticateeventargs E)
{
Authenticateeventhandler handler1 = (authenticateeventhandler) base. events [login. eventauthenticate];
If (handler1! = NULL)
{
// The user uses the custom authentication service
Handler1 (this, e );
}
Else
{
// Use the membership provider
This. authenticateusingmembershipprovider (E );
}
}

Private void authenticateusingmembershipprovider (authenticateeventargs E)
{
// Use loginutil. getprovider to obtain the membership provider object and call its validateuser for authentication.
E. Authenticated = loginutil. getprovider (this. membershipprovider). validateuser (this. usernameinternal, this. passwordinternal );
}

Internal static loginutil. membershipprovider getprovider (string providername)
{
If (string. isnullorempty (providername ))
{
Return membership. provider;
}

// Call the membership attributes to obtain the provider object.
Membershipprovider provider1 = membership. Providers [providername];
If (provider1 = NULL)
{
Throw new httpexception (Sr. getstring ("webcontrol_cantfindprovider "));
}
Return provider1;
}

Role management authorization

In actual development, in addition to the user and role, we also need the permission concept. Roles are more like user groups. Users can join one or more user groups. Each user group has multiple permissions. With permissions, We can dynamically grant different permissions to user groups. For example, we can temporarily grant group A the right to execute XX, and we will cancel this right three days later, obviously, a design without permissions lacks flexibility.

ASP. NET 2.0 role management authorization is composed of rolemanagermodule, roles, roleprovider, and roleprincipa. The system automatically loads the httpmodule rolemanagermodule. Roles provides you with role-related operation methods, while roleprovider is naturally an abstract class of the provider. As for how to use roleprincipa, you can see the following code.

System. Web. Security. rolemanagermodule

Private void onenter (Object source, eventargs)
{
//...
// Note the following code. rolemanagermodule uses roleprincipal to replace the default genericprincipal.
If (! (Context1.user is roleprincipal ))
{
Context1.user = new roleprincipal (context1.user. Identity );
Related Article

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.