Role authentication authorization based on Forms authentication in Asp.net

Source: Internet
Author: User
Tags http cookie

There are three authentication methods for Asp.net: "Windows | forms | passport", among which forms is the most used and most flexible.
Forms
The authentication method provides good support for user authentication and authorization. You can use a login page to verify the user's identity and send the user's identity back to the client's cookie, then the user will access this
The Web application will be sent to the server together with the identity cookie. The authorization settings on the server can control the access authorization of different users according to different directories.

The problem arises. In practice, what we often need is role-based or user group-based authentication and authorization. For a website, the general authentication and authorization mode should be as follows: based on actual needs
Divide the user into different identities, namely roles or user groups. The authentication process not only verifies the identity of the user, but also verifies the role it belongs. Access authorization is based on the role.
Which resources can be accessed by some roles, and which resources cannot be accessed. It would be very impractical to authorize access based on the user. There are many users, which may be increased or decreased at any time.
Add Access Authorization to new users at any time.

The following describes the forms process.

Basic Principles of Forms authentication:

1. Authentication

To use forms authentication, you must firstProgramConfigure the Web. config in the root directory:

<Authentication mode = "forms">
<Forms name = ". aspxauth" loginurl = "/login. aspx" timeout = "30" Path = "/">
</Forms>
</Authentication>

<Authentication mode = "forms"> indicates that the application adopts Forms authentication.
1. Name in the <forms> label indicates the HTTP cookie to be used for identity authentication. By default, the value of name is
. Aspxauth. After the user is verified in this way, a formsauthenticationticket type authentication ticket is created based on the user information, and then the sequence is encrypted.
The string is written to the cookie with the name specified by the client name. Once the cookie is written to the client, the user will access the Web application again
The user will be sent to the server together with the cookie, and the server will know that the user has been verified.

Let's take a look at the information contained in the identity authentication ticket. Let's take a look at the formsauthenticationticket class:
Cookiepath: Return the cookie sending path. Note: the path of the form is set /. The form is case-sensitive, which is a protection measure to prevent the URL in the site from being case-insensitive. This is used when refreshing cookies.
Expiration: Get the cookie expiration date/time.
IspersistenT: If a persistent Cookie has been sent, true is returned. Otherwise, the authentication cookie is restricted within the browser lifecycle.
Issuedate: Get the date/time when the cookie was originally sent.
Name: Obtain the username associated with the authentication cookie.
Userdata: Get the application definition string stored in the cookie.
Version: Returns the byte version number for future use.

2. The loginurl in the <forms> label specifies that if no valid authentication cookie is found
URL. The default value is
Default. aspx. The page specified by loginurl is used to verify the user's identity. Generally, this page provides the user to enter the user name and password. After the user is submitted, the program will follow your own needs.
To verify the validity of the user (most of the time, the user input information is compared with the user table in the database). If the user is verified to be valid, the authentication ticket corresponding to the user is generated, the
Cookie, and finally redirect the browser to the page of the user's initial request. Generally, formsauthentication. redirectfromloginpage is used.
To generate an authentication ticket, write it back to the client, and redirect the browser.

Public static void redirectfromloginpage (string username, bool createpersistentcookie, string strcookiepath );

Where:
Username: Indicates the user's ID. It indicates the unique ID of the user. It is not necessarily mapped to the user account name.
Createpersistentcookie: Indicates whether a persistent cookie is sent.
If it is not a persistent cookie, the expiration attribute of the cookie's validity period includes the current time plus the timeout time in Web. config.
During identity authentication, the system determines whether half of the validity period has passed. If so, the cookie validity period is updated. If the persistence cookie is used, the expiration attribute is meaningless.
The validity period of the verification ticket is determined by the expires of the cookie. The redirectfromloginpage method sets the validity period of 50 years for the expires attribute.
Strcookiepath: Indicates the path to write the generated cookie to the client. The path saved in the authentication ticket is used when the cookie is refreshed (this is also the path for generating the cookie ), if the strcookiepath parameter is not specified, the web. set the path attribute in config.

We can see that there are only three parameters in this method, and there are seven attributes of the identity authentication ticket. The following are the four parameters:
Issuedate: The cookie sending time is determined by the current time,
Expiration: The expiration time is calculated by the current time and the timeout parameter in the <forms> label to be mentioned below. This parameter is valid for non-persistent cookies.
Userdata:This attribute can be used to write some user-defined data. This attribute is not used in this method, but it is simply set to a null string. Please note that this attribute, this attribute will be used later.
Version:The version number is automatically provided by the system.

After the redirectfromloginpage method is used to generate an authentication ticket, formsauthentication. Encrypt is called.
To encrypt the authentication ticket as a string, which is a cookie value named. aspxauth. Other attributes of this cookie are generated.
To: domain, the path attribute is indeed saved, expires depends on the createpersistentcookie parameter, if it is persistent
Cookie. expires after 50 years. If it is a non-persistent cookie, The expires attribute is not set.
After an authentication cookie is generated, add the cookie to response. Cookies and wait for the cookie to be sent to the client.
Finally, the redirectfromloginpage method calls the formsauthentication. getredirecturl method to obtain the page requested by the user and redirect it to this page.

3. the timeout and path in the <forms> label provide the authentication ticket write to the cookie expiration time and default path.

The above process is based on Forms authentication, which completes the confirmation of user identity. The following describes Access authorization based on Forms authentication.

2. Access Authorization

the identity is verified. You can perform different operations and processes based on different identities. The most common thing is to authorize different identities, forms authentication provides the
function. Forms authorization is based on directories. You can set access permissions for a directory. For example, these users can access this directory, and those users cannot access this directory.
Similarly, the authorization settings are in the web under the directory you want to control. in the config file:

roles =" comma-separated list of roles "
verbs =" comma -separated list of verbs "/>
roles =" comma-separated list of roles "
Verbs = "comma-separated list of verbs"/>

<Allow> the label indicates that access is allowed, and Its Attributes
1. Users: A comma-separated list of user names that have been granted access to resources. Question mark (?) Anonymous Users are allowed. asterisks (*) Allow all users.
2. Roles: A comma-separated list of roles that have been granted access to resources.
3. verbs: A comma-separated list of HTTP transfer methods that have been granted access to resources. The predicates registered with ASP. NET are get, Head, post, and debug.

<Deny> the tag indicates that access is not allowed. The attributes are the same as above.

At runtime, the authorization module iterates through <allow> and <deny>
Tag until it finds the first access rule that fits the specified user. Then, it determines whether the first access rule is <allow> or <deny>
Rules to allow or deny access to URL resources. The default authentication rule in the machine. config file is <allow
Users = "*"/>. Therefore, access is allowed by default unless otherwise configured.

So how can these users and roles be obtained? The detailed authorization process is as follows:

1.
Once a user accesses this website, he or she can log on and confirm his or her identity. The cookie of the authentication ticket is also written to the client. Then, this user applies for this web page again, the identity authentication ticket
The cookie is sent to the server. On the server side, Asp.net assigns an httpapplication object for each HTTP request to process the request.
After the httpapplication. authenticaterequest event, the security module has created a user ID, that is, the identity of this user has been established on the Web end
A cookie is created for the authentication ticket sent from the client.
2. the user identity is in the httpcontext. User attribute. On the page, you can use page. Context
To obtain the httpcontext object related to this page. For Forms authentication, the httpcontext. User attribute is a genericprincipal
Type object. genericprincipal has only one public attribute identity, which has a private m_role attribute, which is of the string [] type.
Which role array belongs, and there is a public method isinrole (string role) to determine whether the user belongs to a role.
Because the role attribute is not provided in the cookie of the authentication ticket, that is, the forms authentication ticket does not provide the role information of this user, for Forms authentication, the m_role attribute of the genericprincipal user object obtained on the server is always empty.
3. genericprincipal. Identity
An object of the formsidentity type has a name attribute, which indicates the user. Access Authorization uses this attribute as the user for authorization verification.
Formsidentity has another attribute, namely, the ticket attribute. This attribute is of the formsauthenticationticket type for the authentication ticket, that is, the previous
The authentication ticket that the server writes to the client.
After obtaining the authentication ticket formsauthenticationticket object, the server checks whether the authentication ticket is non-persistent authentication.
The validity period set by the timeout attribute in Web. config to update the cookie of the authentication ticket (to avoid compromising performance, the cookie is updated after more than half of the specified time.
Cookie. This may cause a loss of accuracy. Persistent cookie does not time out .)
4.
Before the httpapplication. resolverequestcache event, Asp.net obtains the page requested by the user and creates
Httphandler control point. This means that in the httpapplication. resolverequestcache event, you need to verify the user's access permissions,
Check whether the user or role has the permission to access this page. Then, it makes no sense to change the identity or role of the user within the lifecycle of this request.

The above is the entire process of forms verification. It can be seen that this forms verification is based on the user and does not provide direct support for role verification. Authentication ticket
Formsauthenticationticket
The name attribute in is the user ID. In fact, there is also the userdata attribute, which can be used by the application to write custom data. We can use this field to store role's
Information to achieve the purpose of Role-based authentication.

Forms authentication role-based authorization

1. Authentication

The <authentication> Settings in Web. config are the same:

<Authentication mode = "forms">
<Forms name = ". aspxauth" loginurl = "/login. aspx" timeout = "30" Path = "/">
</Forms>
</Authentication>

/Login. aspx: after verifying the legality of a user on the user legality page, you also need to have a process of obtaining the role that the user belongs to. It depends on how each application is designed.
Generally, there is a use_role table in the database, which can be obtained from the database. Here, we do not know how to obtain the corresponding role of the user, and finally we will surely get
All the role corresponding to this user is a comma-separated string.
In the above non-role-based method, we use formsauthentication. redirectfromloginpage
To generate an authentication ticket, write it back to the client, and redirect the browser. In this method, a series of actions are completed with some correct settings. We cannot use this method in role-based verification.
Step by step to add some custom settings:

1. Create an authentication ticket based on the user ID and the character string of the user's role.
Public formsauthenticationticket (
Int version,// Set to 1
String name,// User ID
Datetime issuedate,// Set the cookie sending time to datetime. Now.
Datetime expiration,// Expiration time
Bool ispersistent,// Whether it is persistent (set as needed. If it is set as persistent
Cookie expires must be set)
String userdata,// Here, use the prepared role string separated by commas (,).
String cookiepath// Set it to "/", which must be consistent with the cookie sending path, because the cookie is refreshed
Use this path
);

Formsauthenticationticket ticket = new
Formsauthenticationticket (1, "Kent", datetime. Now,
Datetime. Now. addminutes (30), false, userroles ,"/");

2. Generate a cookie for the authentication ticket
2.1 serialize the authentication ticket into a string
String hashticket = formsauthentication. Encrypt (ticket );
2.2 generate cookie
Httpcookie usercookie = new httpcookie (formsauthentication. formscookiename, hashticket );
Formsauthentication. formscookiename is used to obtain the name of the authentication Cookie set in Web. config. The default value is ". aspxauth ".
If the ispersistent attribute in the authentication ticket is set to a persistent class, the expires attribute of the cookie must be set so that the cookie will be saved as a persistent cookie in the cookie file of the client.
3. output the authentication ticket cookie to the client
PassResponse. Cookies. Add (usercookie)Append the authentication ticket cookie to the output Cookie set and send it to the client.
4. Redirect to the user's initial trial page.

VerificationCode(This part of the code is the event processing code by clicking the logon button on the login. ASPX page ):

Private void buttonlogin_click (Object sender, system. eventargs E)
{
String user = textboxuser. text;// Read the user name
String Password = textboxpassword. text; // Read the password
If (confirm (user, password) = true) // The confirm method is used to verify the validity of the user.
{
String userroles = usertorole (User ); // Call the usertorole method to obtain the role string
Formsauthenticationticket ticket = new
Formsauthenticationticket (1, user, datetime. Now,
Datetime. Now. addminutes (30), false, userroles ,"/");// Create an identity authentication ticket object
String hashticket = formsauthentication. Encrypt (ticket ); // The encrypted serialization verification ticket is a string
Httpcookie usercookie = new httpcookie (formsauthentication. formscookiename, hashticket );
// Generate cookie
Context. response. Cookies. Add (usercookie ); // Output cookie
Context. response. Redirect (context. request ["returnurl"]); // Redirect to the initial page of user application
}
Else
{
// Code for unconfirmed user identity
}
}
// This method is used to verify the validity of the user
Private bool confirm (string user, string password)
{
// Corresponding code
}
// This method is used to obtain a comma-separated string for all the role corresponding to the user
Private string usertorole (string user)
{
// Corresponding code
}

2. Role-Based Access Authorization

What we need to do here is to restore the role information saved in userdata in the authentication ticket saved by the client to the genericprincipal object on the server that represents the user's identity (Remember, in the original verification process, the genericprincipal object only contains user information, but does not contain role information)
Httpapplication. the authenticaterequest event indicates that the security module has established a user identity, that is, the identity of this user has been established on the Web end. After this event, we can obtain the user identity information.
Before the httpapplication. resolverequestcache event, Asp.net obtains the page requested by the user and creates
Httphandler control point. Now you have to verify the user's permissions.
Httpapplication. authenticaterequest event and
During the process between httpapplication. resolverequestcache events.
We select application_authorizerequest to do this. We can process all the events of httpapplication in the global. asax file. The Code is as follows:

Protected void application_authorizerequest (Object sender, system. eventargs E)
{
Httpapplication APP = (httpapplication) sender;
Httpcontext CTX = app. context; // Obtain the httpcontext object related to this HTTP Request
If (CTX. Request. isauthenticated = true) // A verified user can process the role.
{
Formsidentity id = (formsidentity) CTX. User. identity;
Formsauthenticationticket ticket = ID. ticket; // Obtain the authentication ticket
String [] roles = ticket. userdata. Split (','); // Convert the role data in the authentication ticket to a String Array
CTX. User = new genericprincipal (ID, roles ); // Add the original identity with the role information to create a genericprincipal to indicate the current user, so that the current user has the role information
}
}

When a visitor has both user and role information, he can use role in Web. config to control the user's access permissions.

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.