Asp.net Forms authentication

Source: Internet
Author: User

There are three authentication methods for Asp.net: "Windows | forms | passport", among which forms is the most used and most flexible.

Forms authentication provides good support for user authentication and authorization. You can use a login page to verify the user's identity and send the user's identity back to the client's cookie, then the user accesses the web application and sends it to the server together with the identity cookie. The authorization settings on the server can control the access authorization of different users according to different directories.

The principle is as follows:

First, authorize the user, such as not allowing anonymous access, and then compare the web. the user name and password configured in config or in the database determine its validity. After the authentication is successful, the user information is saved to the corresponding cookie and added to the client, during the second access, the client sends the user information and creden。 together to the server. If you check that the creden。 are available, you do not need to log on. Otherwise, you will be redirected to the default logon page.

The biggest advantage between it and traditional session + Cookie is that it does not need to judge whether the user exists on every page, saving a lot of repeated code.

The following describes several simple steps for using forms verification.

First, you must configure information in the web. config configuration file, including the Authentication Mode and authorization.

<Authentication mode = "forms">

<Formsname = "adminck" Protection = "all" loginurl = "login. aspx" defaulturl = "default. aspx" Path = "/" timeout = "60">

<Credentialspasswordformat = "clear"> // credential

<Username = "admin" Password = "admin"/>

<Username = "Shuang" Password = "Shuang"/>

</Credentials>

</Forms>

</Authentication>

First, change the Mode authentication method from window to forms. Name in forms is the name of the cookie used to save the authentication information. The default value is. aspxauth and protection are the Processing Methods of user information. When loginurl fails to pass verification or has no creden, it is usually a logon page, defaulturl is the default page that is displayed after successful login verification. path is the path for storing cookies. The default value is "/". This is because most browsers are case sensitive. If the path is case insensitive, the browser does not return the cookie. Timeout indicates the cookie expiration time. The black part stores the user name and password in Web. config. If your user name and password are saved in the database, you do not need to write this section.

Next we need to authorize the user.

<Authorization>

<Denyusers = ""/> reject Anonymous Access

<Denyusers = "Shuang"/> reject Shuang access

<Allowusers = "admin"/> allow Admin Access

</Authorization>

If you are not authorized, at least anonymous access is not allowed, Forms authentication will not work.

 

 

After configuring these parameters in Web. config, you must go to the logon page to verify the user.

Protected voidbutton#click (Object sender, eventargs E)

{

Stringreturnurl = request ["returnurl"];

If (formsauthentication. Authenticate (txtname. Text, txtpwd. Text ))

{

System. Web. Security. formsauthentication. setauthcookie (txtname. Text, true );

Session ["username"] = txtname. text;

If (returnurl = NULL)

{

Formsauthentication. redirectfromloginpage (txtname. Text, false );

}

Else

{

Response. Redirect (returnurl );

}

}

Else

{

This. clientscript. registerstartupscript (this. GetType (), "", "<SCRIPT> alert ('user name or password input error') </SCRIPT> ");

}

}

Returnurl: return the URL of the page you accessed. If yes, you can directly access the page after successful logon.

The validation condition in IF is not necessarily formsauthentication. authenticate (txtname. text, txtpwd. text), this is the verification condition when the user is stored in the configuration file. If it is in the data volume, you can directly call the verification method. After the verification is successful, you can send the user creden:

System. Web. Security. formsauthentication. setauthcookie (txtname. Text, true );

It can be used together with sessions to save user information (Session login and access)

Session ["username"] = txtname. text;

Then determine whether returnurl exists

If (returnurl = NULL)

{

Formsauthentication. redirectfromloginpage (txtname. Text, false );

}

Else

{

Response. Redirect (returnurl );}

Redirectfromloginpage: redirects to the default page after Successful Logon

In this way, the forms verification is basically completed. Pay attention to the following points:

1. It is best to put web. config in the controlled directory. For example, it is usually used in the background, so we can directly put it under admin.

In the Web. config under the root directory, we can put forms verification parameters such:

<Authenticationmode = "forms">

<Formspath = "/" defaulturl = "~ /Admin/admin_index.aspx "loginurl = "~ /Admin/login. aspx"

Timeout = "20" requiressl = "false" cookieless = "usedeviceprofile" name = "hly8_com"

Enablecrossappredirects = "false"> </Forms>

</Authentication>

The Web. config under admin is used for authorization.

<! -- Configure here and log on to the configuration site -->

<Authorization>

<Denyusers = ""/>

</Authorization>

Sometimes we will find that some files or images cannot be accessed ,:

 

This is because you have disabled access to the image directory. Add the following code to the Web. config file:

<Locationpath = "Images">

<! -- Allow everyone to access this page -->

<System. Web>

<Authorization>

<Allow users = ""/>

</Authorization>

</System. Web>

</Location>

2. We can get the user name through user. Identity. Name on other pages. We can use user. Identity. redirectfromloginpage to determine whether the user is logged on.

3. log out and exit, because even if you clear the cookie and go to the logon page, the page is saved in the client, so you can return to the final page when you exit, this is not acceptable. Here we can write like this:

First, destroy the credential: formsauthentication. signout ();

Response. Redirect (request. Path );

In this way, there will be no backoff issues! You can also use the logout control provided by Microsoft

In short, these things should be flexible to use!

 

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.