ASP.NET authentication

xiaoxiao2021-03-20  198

The solution with ASP.NET it can take yourself.

There are three kinds of authentication of ASP.NET, namely "Windows | Forms | Passport", which is mostly used in Forms to verify the most, and most flexible.

The Forms verification method provides good support based on user authentication authorization, can verify the user's identity by a login page, send this user's identity back to the client's cookie, then this user will access this web application will be along with this Identity cookie is sent together to the server. The authorization settings on the server can be controlled for different users' access authorizations according to different directories.

Let's take a look at the process of Forms.

Forms Authentication Basic Principle:

One authentication

To use Forms authentication, you must first make the corresponding settings in Web.config in the application root directory:

Where means that this application uses the Forms authentication mode.

1. Name in the Tag Represents HTTP cookies you want to use for authentication. By default, the value of Name is .aspxauth. After verifying the user in this way, establish a FormSauthenticationalTicket type authentication ticket with this user's information, and then encrypt the sequence into a string, and finally write this string to the cookie of the client's Name specified name. Once this cookie After writing to the client, this user will access this web application again to send along with cookies to the server, the server will know that this user has been verified.

Let's take a look at which information contains, let's take a look at the FormsauthenticationalTicket class:

CookiePath: Returns the path to the cookie. Note that the path to the form is set to /. Since the form is case sensitive, this is a protective measures taken to prevent the case where the URL in the site is inconsistent. This is used when refreshing cookies

Expiration: Get the date / time of the cookie expired.

ISPERSISTENT: Returns true if you have already issued a lasting cookie. Otherwise, the authentication cookie will limit within the browser lifecycle.

Issuedate: Get date / time that originally issued a cookie.

Name: Gets the username associated with authentication cookies.

UserData: Get the application definition string stored in the cookie.

Version: Returns the byte version number for future use.

2. LoginURL in the Tag Specifies that if you do not find any valid authentication cookie, redirect the request to the URL for the login. The default is Default.aspx. LoginURL specified by the page is used to verify the user's identity. Generally, this page provides users enter the username and password. After the user is submitted, the user's legitimacy is verified according to its own needs (most cases, enter the user into the database with the database. The user table is compared.) Generate a series of actions such as authentication tickets, write back to clients, browser redirects.

Public Static Void RedirectFromLoginPage (String Username, Bool CreatePersisteriStentCookie, String StrcookiePath); where:

UserName: This is the logo of this user, which is used to mark the unique indication of this user, not necessarily to map to the user account name.

CreatePersistentCookie: Sign up for a long-lasting cookie.

If you are not a lasting cookie, the Validity period of the cookie has the current time plus the timeout of the timeout. When each request page, during the verification, it will determine whether the validity is half, if you update a cookie Validity period; if it is a lasting cookie, the expression attribute is meaningless. At this time, the validity period of the authentication ticket has a cookie's Expires decision, and the RedirectFromLoginPage method is set to the Expires property of the 50-year validity period.

StrCookiePath: Marking the path to the client to the client, saving this path in the authentication ticket is used when refreshing authentication ticket cookies (this is also generated cookie's Path), if there is no strcookiepath parameter, use Web.config The setting of the Path property.

It can be seen here that this method parameter is only three, and the attributes of authentication tickets have seven, and the four parameters of the insufficient are coming:

Issuedate: cookie issued by the current time,

Expiration: The expiration time is calculated from the current time and the tab you want to say. This parameter makes sense to non-persistent cookies.

UserData: This property can be written to some user-defined data. This method is not used in this property, just simply set this property as an empty string, please note this property, after we will use this property.

Version: The version number is automatically provided by the system.

After generating an authentication ticket, the RedirectFromLoginPage method generates the FormsAuthentication.Encrypt method, encrypts the authentication ticket as a string, which will be the value of a cookie name with .aspxauth. The generation of this cookie's other properties: domain, the Path property is the value of the Value, and the Expires will depend on the cretePersistentCookie parameter. If the lasting cookie, Expires set to 50 years later; if it is not a lasting cookie, the Expires property is not set.

After generating authentication cookies, add this cookie to response.cookies and wait to send to the client.

Final RedirectFromLoginPage method calls the FormSauthentication.getredirectURL method to get the page of the user's original request, redirect to this page.

3. Timeout and path in the "Forms> tab are provided with authentication tickets to the cookie expiration time and default path.

The above is based on Forms authentication process, which completed confirmation of the user identity. Here is an access authorization based on Forms authentication.

Second visit license

Verify the identity, is to use this identity, according to different identities, we can do different operations, process, the most common is to perform different identities, Forms authentication provides such functions. Forms authorization is a directory-based, you can set access to a directory, for example, these users can access this directory, those users cannot access this directory. Similarly, the authorization setting is set in the web.config file in the directory you want to control:

Roles = "Comma-Separated List of Roles"

Verbs = "Comma-Separated List of Verbs" />

Roles = "Comma-Separated List of Roles"

Verbs = "Comma-Separated List of Verbs" />

tag represents allowed access, where the properties

1. Users: A comma-separated username list, which has been granted access to resources. Question mark (?) Allows an anonymous user; as an asterisk (*) allows all users.

2. Roles: A comma-separated list of roles that have been granted access to resources.

3. VERBS: A comma-separated HTTP transmission method list, which has been granted access to resources. The predicates for registration to ASP.NET are GET, HEAD, POST, and DEBUG.

The tag indicates that you are not allowed. The properties are the same.

At runtime, the authorization module iterates through and tag until it finds the first access rule that is suitable for specific users. Then, it allows or reject access to the URL resource based on the first access rule found to be or rules. The default authentication rules in the Machine.config file are , so access is allowed by default unless otherwise configures.

So how do these USER and ROLES get? Let's take a look at the detailed process of authorization:

1. Once a user accesses this website, log in to confirm the identity, and the Cookie of the authentication ticket is also written to the client. After that, this user applies for this web page, and the authentication ticket is sent to the server. At the server, ASP.NET assigns an HTTPApplication object to handle this request. After the httpapplication.authenticateRequest event, the security module has established a user ID, which is that the user's identity has been built, this identity It is completely cookie created by the authentication ticket sent back by the client.

2. User identity In the httpContext.user property, you can get the HTTPContext object associated with this page through page.context in the page. For Forms authentication, the httpContext.user property is an object of GenericPrincipal, and GenericPrincipal has only one public property Identity. It is a private m_role property. It is a string [] type. The user is the array belonging to which Role, there is an open public Method is ISINROLE (String Role) to determine if this user belongs to a role. Since the authentication ticket is not available in the cookie of the authentication ticket, it is said that the Forms authentication ticket does not provide this user's role information, so for Forms verification, the M_Role properties of the genericprincipal user objects received in the server are always empty.

3. GenericPrincipal. Identity property is an object of a FormSIDETY type. This object has a Name property, which is the name of this user. Access authorization is to perform this property as a User to authorize authentication. FormSident has a property, which is a Ticket property. This property is the authentication ticket FormSauthenticationalTicket type, which is previously written to the client's authentication ticket.

After getting the authentication ticket FormsAuthenticationalTicket object, it is not a long-lasting authentication. If you want to update this authentication ticket according to the validity period set by the timeout property in Web.config (to avoid endanger performance This cookie is updated after more than half of the specified time. This may result in the loss of preciseness. Persistent cookie does not timeout.)

4. Before the httpapplication.resolverequestCache event, ASP.NET starts obtaining the page of the user requested to establish the HTTPHANDLER control point. This means that at the httpapplication.resolverequestCache event to verify user access, see if this user or role has permission to access this page, then change this user's identity or role in this request lifecycle. .

The above is the whole process of Forms verification, it can be seen that this Forms verification is based on the user's, and there is no direct support for the validation of the role. The name attribute in the FormsauthenticationalTicket is the user's name, in fact, there is still a property userData, which can be written to customized data by the application, we can use this field to store the role-based information based on role verification the goal of.

Forms authentication based on role authorization

One authentication

Is the same or the same as Web.Config's :

/Login.aspx Verified the user's legitimacy page, after verifying the user's legitimacy, there must be a process of which the user belongs to which Role is, this is what the app it is designed, usually in the database There is a USE_ROLE table that can be obtained from the database to which Role belongs, where it is not taken to get the user's corresponding Role, and finally you can obtain a string with a comma-split of all the ROLLEs. In the above non-role method, we use the Formsauthentication.RedirectFromLoginPage method to complete a series of actions such as generating authentication tickets, write back to clients, browser redirection. This method uses some of the province settings to complete a series of actions. In role-based verification, we cannot use this method to achieve, to step by step to add some custom settings:

1. First create an authentication ticket according to the user's marking, and the character string of the user belongs to

Public FormsauthenticationTicket

INT version, / / ​​set to 1

String name, // user

DateTime Issuedate, // Cookie's issuance time, set to datetime.now

DateTime expiration, // expiration time

Bool ispersistent, // is persistent (set as needed, if set to persistence,

When cookies, cookie's Expires settings must be set)

String UserData, // Here is prepared with a comma-divided role string with a comma

String cookiepath // is set to "/", this is the same as the path to the cookie, because refreshing cookie

To use this path

);

FormsauthenticationalTicket Ticket = New FormsauthenticationTicket (1, "Kent", DateTime.Now, DateTime.Now.addminutes (30), False, Userroles, "/");

2. Generate the cookie of authentication ticket

2.1 Sequence of authentication tickets into a string

String hashticket = formsauthentication.encrypt (ticket);

2.2 Generate Cookie

Httpcookie usercookie = new httpcookie (formsauthentication.formie (formsauthentication.formie);

FormSauthentication.FormScookiename is used to get the name of authentication cookie set in Web.config, default is ".aspxauth".

If the ISPERSIStent property in the authentication ticket is set to a lasting class, this cookie's Expires property must be set so that this cookie will be saved as a Cookie file that lasted Cookies to the client.

3. Output Authentication tickets to the client

Send the authentication ticket cookie to the output cookie collection via Response.Cookies.Add (userCookie) to send to the client.

4. Redirect to the initial test page for the user.

Verify partial code (this part of the code is on the login.aspx page, click the login button event processing code):

Private Void ButtonLogin_Click (Object Sender, System.EventArgs E)

{

String user = textboxuser.text; // read username

String password = textBoxpassword.text; // read the password

IF (confirm (user, password == true) // Confirm method is used to verify the legality of the user {

String UserRoles = UserTorole (user); // Call the Usertorole method to get the Role string

FormsauthenticationticTicket Ticket = New FormsauthenticationTicket (1, User, DateTime.now, DateTime.now.addminutes (30), False, Userroles, "/"); // Establish an authentication ticket object

String Hashticket = FormSauthentication.Encrypt (Ticket); // Encrypted Serialization Verification Ticket is a string

Httpcookie usercookie = new httpcookie (formsauthentication.formie (formsauthentication.formie);

/ / Generate cookie

Context.Response.cookies.add (usercookie); // Output cookie

Context.Response.Redirect (Context.Request ["ReturnURL"]); / / Redirect to the initial page to the user

}

Else

{

// User identity is not confirmed by the code

}

}

// This method is used to verify the legitimacy of the user.

Private Bool Confirm (String User, String Password)

{

// Corresponding code

}

// This method uses all the ROLE-divided strings of the user corresponding to the user.

Private string UserTorole (String User)

{

// Corresponding code

}

Two based on role access authorization

What we have to do this is that the information saved in the userData saved in the user-saved authentication ticket is restored to the GenericPrincipal object indicating the user's identity (remember, the genericprincipal object is only included during the original verification process. User information, does not contain role information)

During an HTTP request, httpapplication.authenticateRequest event indicates that the security module has established a user ID, that is, the user's identity has been established in the web end, after this event we can get user identity information.

Before the httpapplication.resolverequestCache event, ASP.NET starts obtaining the page of the user request, establish an HTTPHANDLER control point, then verify the user's permissions, so restoring the user role work can only be in httpApplication.authenticateRequest event and httpApplication.resolverequestCache During the process between events.

We choose to do this in the Application_AuthorizeRequest event, you can handle all the events of HTTPApplication in the global.asax file, the code is as follows:

Protected Void Application_AuthorizationRequest (Object Sender, System.Eventargs E)

{

HTTPApplication APP = (httpapplication) Sender;

HTTPCONTEXT CTX = App.Context; // Get httpContext objects related to this HTTP request

If (ctx.request.isauthenticated == true) // Verified users to process ROLE processing

{

Formsidentity ID = (FormSIDENTITY) CTX.User.Identity;

Formsauthenticationticket Ticket = id.ticTicket; // Take authentication ticket String [] Roles = Ticket.UserData.split (','); // Transfer the Role data in the authentication ticket into a string array

CTX.user = new genericprincipal (id, roles); // Add a geneticPrincipal, add a genericprincipal, which is the current user, so that the current user has Role information.

}

}

Visitors have User and Role messages, so that it can be used to control users' access rights in Web.config.

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

New Post(0)