Asp.net login verification Form verification methods FormsAuthentication. SetAuthCookie; FormsAuthentication. RedirectFromLoginPage; FormsAuthenticationTicket,

Source: Internet
Author: User

Asp.net login verification Form verification methods FormsAuthentication. SetAuthCookie; FormsAuthentication. RedirectFromLoginPage; FormsAuthenticationTicket,

After successful login, we use the following three methods for the same purpose: to create an authentication ticket and attach it to the Cookie,

HttpContext can be used for Forms authentication. current. user. identity. isAuthenticated (or you can use Request. isAuthenticated, which is actually called by User. identity. isAuthenticated to verify) to determine whether to log on. This judgment depends on the information in this Cookie to determine whether the user logs on.
FormsAuthentication. SignOut is used to clear this Cookie flag

Form authentication depends on cookies. Asp.net checks the Cookie name specified in the configuration file and decrypts the Cookie to determine the login status of the currently requested user.

The premise of using the following three methods is to set form verification in web. config.

 

<authentication mode="Forms">            <forms name=".MyCookie" loginUrl="Login.aspx" protection="All" timeout="60"/>        </authentication> 

 

1: FormsAuthentication. SetAuthCookie

Demo:

 

FormsAuthentication.SetAuthCookie(UserInfo.UserName, false, FormsAuthentication.FormsCookiePath);


 

 

[System. web. security. formsAuthentication. setAuthCookie ("fish", false);] After Asp.net does something, it is actually very easy to answer this question: Use reflector.exe to check the implementation of Asp.net.
To make you more convinced that logon is related to cookies, I will create a Cookie to check whether Asp.net can recognize the Cookie I have created and believe that the logon is valid. See the Code:

If you run this code, you will find that: [Request. IsAuthenticated] returns true, and the logon status displays "logged on ".
So far, we can draw a conclusion: Form authentication relies on cookies. Asp.net is the Cookie name we specify in the configuration file each time, the Cookie is decrypted to determine the login status of the currently requested user.

2: FormsAuthenticationTicket

Demo:

/// Create an authentication ticket FormsAuthenticationTicket AuTicket = new FormsAuthenticationTicket (1, UserInfo. userName, DateTime. now, DateTime. now. addMinutes (30), false, Request. userHostAddress); // encrypt the ticket string authTicket = FormsAuthentication. encrypt (AuTicket); // Save the encrypted ticket as cookie HttpCookie coo = new HttpCookie (FormsAuthentication. formsCookieName, authTicket); coo. secure = false; coo. expires = AuTicket. expiration; coo. path = FormsAuthentication. formsCookiePath; // Add the new cookie Response. cookies. add (coo );

 

 

3: FormsAuthentication. RedirectFromLoginPage

Demo:

FormsAuthentication.RedirectFromLoginPage(UserInfo.UserName, false);

Note:

Name Description
FormsAuthentication. RedirectFromLoginPage (String, Boolean) Redirects authenticated users back to the original requested URL or default URL.
FormsAuthentication. RedirectFromLoginPage (String, Boolean, String) Use Forms to authenticate the specified Cookie Path and redirect authenticated users back to the original requested URL or default URL.

 

The second parameter of FormsAuthentication. RedirectFromLoginPage. true indicates that the persistent cookie is retained. The expiration time is the time in web. config. If it is false, the browser will expire when it is disabled.

This line of code enables you to enter the login name and password, and then go to the page you originally thought.

The following parameter "false" indicates whether the cookie is permanently retained. True indicates that the password is permanently retained. You do not need to enter the password for the next visit. Otherwise, you need to enter the password next time after disconnecting the link. This parameter can also be selected by the user. Considering the security, you can place a checkbox beside the user name or password. The original statement can be:

System.Web.Security.FormsAuthentication.RedirectFromLoginPage(this.txt name. Text, this. CheckBox. Checked );

 

 

 

RedirectFromLoginPage and FormsAuthenticationTicket

If you are not clear about. net authentication, read this article. This article uses a simple and clear language to give you a complete understanding of RedirectFromLoginPage and FormsAuthenticationTicket.
1) FormsAuthentication. RedirectFromLoginPage (UserName. Text, mycheckbox. Checked) is used for user-based authentication. 
This method encapsulates a series of actions, such as generating authentication tickets, writing back to the client, and browser redirection.
The RedirectFromLoginPage () method first generates an authentication ticket and then calls FormAuthenticaiton. encrypt () method, which encrypts the authentication ticket as a string, generates an authentication Cookie, and then adds the Cookie to Response. cookies are waiting 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.
1. Create a cookie in the browser, which contains a verification token.
2. Return to the page you just requested;
It is equivalent to the following two sentences:
FormsAuthentication. SetAuthCookie (UserName. Text, mycheckbox. Checked );
Response. Redirect (FormsAuthentication. GetRedirectUrl (UserName. Text, mycheckbox. Checked );
That is to say, the FormsAuthentication. RedirectFromLoginPage method is equivalent to an encapsulated method, which simplifies many details.

2) FormsAuthenticationTicket, used for role-based Identity Authentication 
In the preceding non-role-based method, the FormsAuthentication. RedirectFromLoginPage method is used to generate an authentication ticket, write it back to the client, and redirect the browser. This method will complete a series of actions with some real-time settings. In role-based verification, we cannot use this method for implementation. It should be done step by step, to add 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, // Cookie sending time, set to DateTime. Now
DateTime expiration, // expiration time
Bool isPersistent, // whether it is persistent (set as needed. If it is set to persistent
Cookie Expires must be set)
String userData, // The role string prepared above that is separated by commas (,).
String cookiePath // set to "/", which must be the same as 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
Use Response. Cookies. Add (UserCookie) to 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.

Verify some code (this 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 authentication Ticket object
String HashTicket = FormsAuthentication. Encrypt (Ticket); // The encrypted serialization validation 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 the 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
}

3) Summary
Step 5:
1. Create an authentication ticket
2. Encrypted authentication tickets
3. Generate Cookie
4. Cookie output to the client
5. Page redirection

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.