ASP. 3 Ways to verify form form formsauthentication.setauthcookie;formsauthentication.redirectfromloginpage; FormsAuthenticationTicket

Source: Internet
Author: User
Tags ticket

After the successful landing, we use the following 3 methods, all of which are the same purpose: to create an authentication ticket and attach it to a Cookie,

When we use Forms authentication method, can use HttpContext.Current.User.Identity.IsAuthenticated (or can also use request.isauthenticated, This is actually called the User.Identity.IsAuthenticated to verify the login, and the judgment is dependent on the information in this cookie to determine whether the user is logged in.
FormsAuthentication.SignOut used to clear this cookie tag

Form authentication relies on cookie,asp.net to check the cookie name that we specify in the configuration file and decrypt the cookie to determine the login status of the current requesting user.

The following 3 methods are used if you set the form validation in Web. config

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

1:formsauthentication.setauthcookie

Demonstrate:

Formsauthentication.setauthcookie (Userinfo.username, False, Formsauthentication.formscookiepath);




"System.Web.Security.FormsAuthentication.SetAuthCookie (" fish ", false);" After what did ASP. The answer to this question is simple: use Reflector.exe to see the implementation of ASP.
Here in order to make it more convincing that you are logged in with a cookie, I will create a cookie directly to see if ASP is able to recognize the cookie I created and that the login is valid. Please look at the code:

If you execute this code, you will find: "request.isauthenticated" returns True, and the login status displays "logged in."
At this point, we can conclude that form authentication relies on cookie,asp.net to check the cookie name that we specify in the configuration file and decrypt the cookie to determine the login status of the current requesting user.

2:formsauthenticationticket

Demonstrate:

Create an authentication ticket   formsauthenticationticket auticket =new formsauthenticationticket (1, Userinfo.username, DateTime.Now, DateTime.Now.AddMinutes (+), false, request.userhostaddress); Encrypt the ticket  string authticket = Formsauthentication.encrypt (auticket);////Save the encrypted ticket as a cookie  HttpCookie COO = New HttpCookie (Formsauthentication.formscookiename, AuthTicket); Coo. Secure =false; Coo. Expires = auticket.expiration; Coo. Path = Formsauthentication.formscookiepath; Add New Cookie  Response.Cookies.Add (COO);

3:formsauthentication.redirectfromloginpage

Demonstrate:

FormsAuthentication.RedirectFromLoginPage (Userinfo.username, false);

Comments:

name Description
FormsAuthentication.RedirectFromLoginPage (String, Boolean) Redirects an authenticated user back to the originally requested URL or the default URL.
FormsAuthentication.RedirectFromLoginPage (String, Boolean, String) Redirects an authenticated user back to the originally requested URL or default URL using the specified cookie path of the Forms authentication cookie.

The second parameter of FormsAuthentication.RedirectFromLoginPage, true indicates that persistent cookies are preserved, the expiration time is the time in Web. config, and if False, the browser is closed and expires.

This line of code implementation after you fill in the login name and password, the success will go to the original page you think of.

The argument "false" after this indicates whether the cookie is persisted. True means permanent retention, the next visit will not enter a password, or disconnect the link, the next time you need to enter a password. This parameter can also be selected by the user, because security, you can put a checkbox beside the user name or password, the original statement can be:

System.Web.Security.FormsAuthentication.RedirectFromLoginPage (this.txtname.text,this. checkbox.checked);

The difference between RedirectFromLoginPage and FormsAuthenticationTicket

If you are not clear about. NET authentication, see this article. This article uses the simple and clear language, lets you have a complete understanding to the RedirectFromLoginPage and the FormsAuthenticationTicket.  
1) formsauthentication.redirectfromloginpage (Username.text, MyCheckBox. Checked) for user-based authentication  
This method encapsulates a series of action   that generate an authentication ticket, write back to the client, redirect the browser, and so on;
RedirectFromLoginPage () The Formauthenticaiton.encrypt method generates an authentication ticket first, and then calls the method, which encrypts the authentication ticket to a string and then generates an authentication cookie. This cookie is then added to the Response.Cookies, waiting to be sent to the client. Finally, the RedirectFromLoginPage method calls the Formsauthentication.getredirecturl method to obtain the page that the user originally requested, redirecting to this page.  
1. Create a cookie on the browser that contains a validation token.  
2, return the page you requested just now;  
corresponds to these two sentences:  
Formsauthentication.setauthcookie (Username.text,mycheckbox. Checked);  
Response.Redirect (Formsauthentication.getredirecturl (Username.text,mycheckbox. Checked);  
that is, the FormsAuthentication.RedirectFromLoginPage method is equivalent to a encapsulated method, simplifying a lot of detail.

2) FormsAuthenticationTicket for role-based authentication
The above non-role-based approach, using the FormsAuthentication.RedirectFromLoginPage method to complete the generation of authentication tickets, write back to the client, browser redirection and a series of actions. This method accomplishes a series of actions with a set of exact provinces, which we cannot do with this method in role-based validation, in order to add some custom settings:

1. First create an authentication ticket based on the user ID and the string of the role that the user belongs to
Public FormsAuthenticationTicket (
int version,//set to 1
String name,//user identifier
DateTime issuedate,//cookie time, set to DateTime.Now
DateTime expiration,//expiry time
BOOL Ispersistent,//whether persistent (as required, if set to persistent, in the issue
Cookie, the expires setting of the cookie must be set)
String UserData,//This is a comma-separated role string prepared here
String Cookiepath//is set to "/", which is consistent with the path of the cookie being issued because the cookie is refreshed
To use this path
);

FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket (1, "Kent", DateTime.Now, DateTime.Now.AddMinutes (30) , False,userroles, "/");

2. Generate the cookie for the authentication ticket
2.1 Encrypt the authentication ticket into a string
String hashticket = Formsauthentication.encrypt (Ticket);
2.2 Generating cookies
HttpCookie Usercookie = new HttpCookie (Formsauthentication.formscookiename, Hashticket);
The formsauthentication.formscookiename is used to obtain the name of the authentication cookie set in Web. config, and the default is ". Aspxauth ".
If the Ispersistent attribute in the authentication ticket is set to a persistent class, the Expires property of the cookie must be set so that the cookie is persisted as a persistent cookie in the client's cookie file.
3. Export the authentication ticket cookie to the client
The authentication ticket cookie is appended to the output cookie collection via RESPONSE.COOKIES.ADD (Usercookie) and sent to the client.
4. Redirect to the preliminary interview page of the user request.

Verify that part of the code (this part of the code is clicked on the Login button event handling code on the Login.aspx page):

private void Buttonlogin_click (object sender, System.EventArgs e)
{
string user = Textboxuser.text; Read user name
string password = Textboxpassword.text; Read 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
FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket (1,user,datetime.now, DateTime.Now.AddMinutes (30 ), False,userroles, "/"); Establish an authentication ticket object
String hashticket = Formsauthentication.encrypt (Ticket); Encrypt serialized validation ticket as String
HttpCookie Usercookie = new HttpCookie (Formsauthentication.formscookiename, Hashticket);
Generate cookies
CONTEXT.RESPONSE.COOKIES.ADD (Usercookie); Output cookie
Context.Response.Redirect (context.request["RETURNURL"]); Redirect to initial page of user request
}
Else
{
Code when the user's identity is not acknowledged
}
}
This method is used to verify the legality of the user
private bool Confirm (string user,string password)
{
The corresponding code
}
This method is used to get all the role of the user corresponding to a comma-separated string
private string Usertorole (string user)
{
The corresponding code
}

3) Summary
Authentication 5-Step walk:
1. Create an authentication ticket
2. Encrypt authentication ticket
3. Generate cookies
4, the cookie output to the client
5. Page redirection

ASP. 3 Ways to verify form form formsauthentication.setauthcookie;formsauthentication.redirectfromloginpage; FormsAuthenticationTicket

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.