Froms authentication method in ASP.

Source: Internet
Author: User
Tags http cookie httpcontext ticket

Microsoft's ASP. NET provides 3 user authentication methods, namely, Windows Authentication, forms (forms) validation, and passport validation.

Because of the different authentication methods, so the 3 kinds of authentication methods in the scope of use is also very big difference, Windows authentication method only applies to the site in the controlled environment; That is, more appropriate for the enterprise intranet (intranet). Form certification is particularly suitable for the application of the Internet, and the Passport authentication method suitable for cross-site applications, the user only with a user name and password can access any member station, and at the time of departure, all passport information will be cleared, you can be assured in public use. When we were writing a Web program, we used most of the forms validation, and Microsoft provided simple forms validation as long as a simple configuration Web. config file could be implemented. In order to better use the form verification, I have studied this kind of verification method.

namespaces for forms-based authentication classes: System.Web.Security Several commonly used classes are: 1. FormsAuthentication role: Managing Forms Authentication Services for WEB applications 2. FormsAuthenticationTicket  Role: Provides access to the properties and values of the ticket, which is used for Forms authentication to identify the user 3. FormsIdentity  Role :Represents a user identity that is authenticated by using Forms authentication. (user identity) 4. FormsAuthenticationModule role: Setting the identity of an ASP. User with Forms authentication one, simple authentication method First, we can configure the Web. config file to implement a simple authentication method. Build a Web project first, and then put the login control on the home page. Then in this project to create a directory, in this directory to add two Web pages, set up in this directory of the page can only be accessed after verification. In the Default.aspx page, enter the user name and password, and click, if the password and username are correct, you can go to a page in the new directory by verifying it. If you do not pass validation, you cannot access the page under the directory. The code is as follows: Void Logon_click (object sender, EventArgs e)
{
String UserName = Useremail.text;
String userpass = Userpass.text;

if (the user and password are judged correctly by connecting to the database)
{
Redirect an authenticated user back to the originally requested URL or the default URL
FormsAuthentication.RedirectFromLoginPage (UserName, PERSIST.CHECKD);
Does this function create a cookie: FIX: Create a cookie
Else
{
Msg.text = Invalid credentials. Please try again. ";
}
Then in the created directory, create a new Web. config file <configuration>
<system.web>
<authorization>
<deny users= "?"/> not allow access by unauthenticated users
</authorization>
</system.web>
</configuration> in this Web. config file, set the authorization method for all files in this directory. This is a URL authorization. The application checks for anonymous users based on the configuration. URL authorization is defined within the <authorization> section in Web. config. There are two tags in the <authorization></authorization> section that mark <allow> define the users, tasks, and actions that are included in the <deny> tag for users who are not allowed, Tasks and actions. For example: <allow users = "*" > <deny users = "?" >
"*" On behalf of all users, "?   "Represents an anonymous (unauthenticated) user. In Web. config under headlines, we also set the authentication method to be based on forms <authentication mode= "forms" >
<forms loginurl= "logon.aspx" name= ". Aspxformsauth "></forms>
</authentication>
<authorization>
<allow users= "*"/>
</authorization>
Valid attribute of the <forms> element name: The name of the HTTP cookie used for authentication. Loginurl: The login page to which the user will be redirected without a pass-through verificationthe URL.The method of Protection:cookie data protection. The expiration time of the Timeout:cookie, in minutes. The default value is 30path:path for the path where the cookie was issued.  The default value is "/". Ii. Implementing complex authentication Methods (role control) constructs GenericPrincipal and FormsIdentity object GenericPrincipal: Represents a generic user formsidentity: Represents a use of Forms The authentication authenticated user identity FormsIdentity class is used by FormsAuthenticationModule when authenticating a user through Forms authentication. Creates an instance of FormsIdentity using FormsAuthenticationTicket decrypted from the Forms authentication Cookie or URL. Then, using a new instance of this formsidentity class to construct a new GenericPrincipal object, the object will be set to the value of the current HttpContext user property in the Global.asax file, adding the event Application_ AuthenticateRequest Code: NOTE: Application_AuthenticateRequest adds custom authentication code to this event. 1, the page requests to obtain the cookie and the role value using System.Web.Security;
Using System.Security;
This event is used to obtain cookie and role values for page requests
protected void Application_authenticationrequest (object sender, EventArgs e)
{
Request a form authentication cookie in the collection of passed cookies
FormsCookieName: Gets the cookie name used to store the forms authentication ticket

FormsCookieName for referencing cookies that store formsauthenticationticket information
string cookiename = Formsauthentication.formscookiename;

Provides type-safe methods for creating and manipulating each HTTP Cookie
HttpCookie class gets and sets the properties of each cookie

HttpCookie cookie = Reauest.cookies[cookiename];/* Get cookie*/from CookieName

if (cookie = = null)
Return
Extracting and decrypting authentication tickets from the Forms authentication cookie
FormsAuthenticationTicket ticket = null;

Try
{
Return value: A FormsAuthenticationTicket object
Ticket = Formsauthentication.decrypt (cookie.  Value); Cookie: Encrypted authentication ticket
}
catch (Exception err)
{
Return
}

if (ticket = = null)
Return

Resolves a list of role names that the user attaches to the ticket when the user is initially authenticated
string[] roles = ticket. Userdata.split (New char[]{' | '});


Creates a FormsIdentity object and a GenericPrincipal object. The previous object from the ticket name
Get the user name, and the latter object contains this identity together with the list of user roles
FormsIdentity ident = new formsidentity (ticket);

GenericPrincipal princ = new GenericPrincipal (ident, roles);
HttpContext.Current.User = Princ;
}

2, login can get user information and whether you have logged in

Verify and obtain user information
private void Page_Load (object sender, System.EventArgs e)
{
FormsIdentity useridentiy;
FormsAuthenticationTicket Objtecket;

if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
             useridentiy = httpcontext.current.user.identity;
            objTecket =  Useridentiy.ticket;
            //can get user information from ticket
         }
        else
         {
             response.write ("<script>alert (' You did not log in! '); History.back () </script> ");
            //or point to the login page
             response.redirect ("Login.aspx");
        } 
}

3. Generate user ticket at login

private string Authorization (string username, string password)
{
User Login Verification
string ip = System.Web.HttpContext.Current.Request.UserHostAddress;
String name = Username;
string pwd = password;

if (validatepwd (name, pwd) = true)//database validation, code slightly
{
Create an authentication ticket
FormsAuthenticationTicket ticker = new FormsAuthenticationTicket (1, name, DateTime.Now,
DateTime.Now.AddMinutes (+), False, "");

String encryptticket = Formsauthentication.encrypt (ticker);
HttpCookie cookie = new HttpCookie (Formsauthentication.formscookiename, Encryptticket);
Reponse.appendcookie (cookie);

Redirect the user to the original request page
Response.Redirect (Formsauthentication.getredirecturl (name, false));

Resonse.redirect (FormsAuthentication.RedirectFromLoginPage (name, false));
This. session["UserName"] = UserName;
}
Else
{
Response.Write ("<script>alert (' your username or password error ');</script>");
}
}

Explain:

Context.User.Identity.IsAuthenticated

Context: Gets the System.Web.HttpContext object associated with the page

User: Gets or sets security information for the current HTTP request

Identity: Gets the identity of the current user

IsAuthenticated: Gets a bool value that indicates whether the user is authenticated

Froms authentication method in ASP.

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.