Authentication knowledge in ASP. NET and basic usage of login controls

Source: Internet
Author: User

Sometimes, some pages on one of our sites must be logged on to the user before they can be accessed. At this time, we need to verify whether the user has logged on. In addition, after the user completes the operation, there must be a mechanism for the user to return. The traditional method is to use cookies to save the login information. If the information cannot be found on the user's machine, access is denied. In ASP. NET, since it is a web development framework, this function should be encapsulated to be more powerful and easy to use. This is called form verification.

 

To implement Form Verification in ASP. NET, follow these two steps:

 

1: Prepare a logon page. Since you cannot access a page without a logon user, you must jump to the logon page. This is a reasonable solution.

2: Configure related items in Web. config.

 

The following is an example of a logon page:

 

        protected void btLogIn_Click(object sender, EventArgs e)
        {
            string userName = txUserName.Text;
            string password = txPswd.Text;
           
            using(StreamReader sr = File.OpenText
        ("D:\\My Documents\\Visual Studio 2008\\Projects\\Project1\\MyWebIM\\MyWebIM\\user info.txt"))
            {
                string input =null;
                while((input=sr.ReadLine())!=null)
                {
                    if (input == userName)
                    {
                        input = sr.ReadLine();
                        if (input == password)
                        {
                            User currUser=new User(userName,password);
                            Global.MyHome.adduser(currUser);
                            FormsAuthentication.RedirectFromLoginPage(userName, false);
                            break;
                        }
                    }
                }
            }
        }

The key is this line:

Formsauthentication. redirectfromloginpage (username, false );

This line tells ASP.. NET environment. If the user authentication is successful, set a valid cookie for the current user and switch to the Web. the default value defined in the config file is on the page.

It has completed at least the following tasks:

1: it creates a verification ticket for the user,

2: it encrypts the information in the ticket,

3: it creates a cookie to save the encrypted ticket,

4: It adds the cookie to the HTTP Response and sends it to the client,

5: It redirects the user to the page of the original request (included in the query string parameter of the login page request URL ).

The second parameter of this method indicates whether a persistent cookie should be created. The persistent cookie is stored in the user's hard disk and can be reused during subsequent access.

The definition in Web. config is as follows:

<Authenticationmode = "forms">
<Forms
Defaulturl = "userhome. aspx"
Loginurl = "login. aspx"
/>
</Authenticationmode>

 

<Location Path = "userhome. aspx">
<System. Web>
<Authorization>
<Deny users = "? "/>
</Authorization>
</System. Web>
</Location>

The first block is available on the default page generated by vs2008, but it is commented out. Just release it, however, delete the authorization section below, because it specifies that all pages cannot be accessed by anonymous users, and the images or other resources on the logon page cannot be displayed. Therefore, you must separately set authorization for other pages, excluding logon pages. The setting method is shown in the second section.

After this process, you can directly enter the userhome. aspx address shown above in the browser, and you will be unable to access it. Instead, the loginurl: Login. ASPX page will be automatically redirected to our designated loginurl. In this way, our logon restrictions are added. The following describes how to exit a user.

 

To exit, simply add a log off button or other things somewhere on the page, and then add the following response code:

 

Formsauthentication. signout ();
Formsauthentication. redirecttologinpage ();

 

You can understand what this means.

 

There are still many details about form verification and the security issues to be taken into account. First wide, then deep.

For more information about the login control, see ASP. NET 2.0 secrets (Volume 2) login control overview.

 

My own login control experiment process:

1: Create a blank website,

2: change default. aspx to login. aspx.

3: Configure web. config:

Join:

 

<Authentication mode = "forms">
<Forms>
<Credentials passwordformat = "clear">
<User name = "bill" Password = "secret"/>
<User name = "Ted" Password = "secret"/>
</Credentials>
</Forms>
</Authentication>

 

This is placed under system. Web, and then:

 

<Location Path = "secret. aspx">
<System. Web>
<Authorization>
<Deny users = "? "/>
</Authorization>
</System. Web>
</Location>

 

This is placed outside system. Web.

 

4: The main contents of login. aspx are as follows:

 

<Head runat = "server">
<Title> untitled page </title>
<Style type = "text/CSS">
. Login
{
Width: 250px;
Font: 14px verdana, sans-serif;
Background-color: Gray;
Border: solid 3px black;
Padding: 4px;
}
. Login_title
{
Background-color: Silver;
Color: black;
Font-weight: bold;
}
. Login_instructions
{
Font-size: 12px;
Text-align: left;
Padding: 10px;
}
. Login_button
{
Border: solid 1px black;
Padding: 3px;
}
</Style>
</Head>
<Body>

<Form ID = "form1" runat = "server">
<Div>
<Asp: Login ID = "login1" instructiontext = "Please log in before accessing the premium section of our website ."
Onauthenticate = "login1_authenticate"
Titletext = "log in"
Textlayout = "textontop"
Loginbuttontext = "log in"
Displayrememberme = "true"
Cssclass = "login"
Titletextstyle-cssclass = "login_title"
Instructiontextstyle-cssclass = "login_instructions"
Loginbuttonstyle-cssclass = "login_button"
Runat = "server"

Destinationpageurl = "secret. aspx"/>
</Div>
</Form>
</Body>
</Html>

 

5: Login. aspx. CS defines the verification function mentioned above: login1_authenticate is as follows:

 

Protected void login=authenticate (Object sender, authenticateeventargs E)
{
String username = login1.username;
String Password = login1.password;
E. Authenticated = formsauthentication. Authenticate (username, password );

}

 

6: Prepare a website that does not allow external access without logon. Of course, the name is destinationpageurl = "secret. the secret specified by the aspx property. the aspx attribute is used to directly access login. the default jump page after logging on to the ASPX page. The default value is default. aspx, but now the project has not prepared this, so let it jump to this for the time being. If you directly access an internal page, first jump to login. aspx. After Successful Logon, the initial access page is displayed.

 

7: you can log on with the username and password set in the preceding configuration file...


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.