[. Net role-based security authentication] 3: ASP. NET Forms authentication

Source: Internet
Author: User
Tags http cookie
In the development process, we need to do the following:

1. Set parameters related to Forms authentication in Web. config.
2. Create a logon page.

Operations on the logon page include:

1. Verify that the user name and password are correct.
2. Create an authentication ticket object.
3. encrypt the authentication ticket object into a string and write it into cookies.
4. Redirect to the original request URL.

1. Simple demonstration

Web. config

<? XML version = "1.0"?>
<Configuration>
<System. Web>
<Compilation DEBUG = "true"/>
<Authentication mode = "forms">
<Forms loginurl = "~ /Logon. aspx "name =" myauthform ">
<Credentials passwordformat = "clear">
<User name = "username" Password = "password"/>
</Credentials>
</Forms>
</Authentication>
<Authorization>
<Deny users = "? "/>
</Authorization>
</System. Web>
</Configuration>

Logon. aspx

<% @ Page Language = "C #" %>
<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<SCRIPT runat = "server">
Protected void button#click (Object sender, eventargs E)
{
If (formsauthentication.authenticate(this.txt username. Text, this.txt password. Text ))
Formsauthentication.redirectfromloginpage(this.txt username. Text, true );
Else
Response. Write ("the user name or password is incorrect! ");
}
</SCRIPT>

<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> logon page </title>
</Head>
<Body>
<Form ID = "form1" runat = "server">
<Div>
Username: <asp: textbox id = "txtusername" runat = "server" width = "100px" text = "username"> </ASP: textbox> <br/>
Password: <asp: textbox id = "txtpassword" runat = "server" width = "100px" text = "password"> </ASP: textbox> <br/>
<Asp: button id = "button1" runat = "server" text = "sign in" onclick = "button#click"/>
</Div>
</Form>
</Body>
</Html>

2. Forms verification parameters

If authentication is required for page access requests in some subdirectories, you can modify web. config in the root path.

Web. config

<? XML version = "1.0"?>
<Configuration>
<System. Web>
<Compilation DEBUG = "true"/>
<Authentication mode = "forms">
<Forms loginurl = "~ /Logon. aspx "name =" myauthform ">
<Credentials passwordformat = "clear">
<User name = "username" Password = "password"/>
</Credentials>
</Forms>
</Authentication>
<Authorization>
<Allow users = "*"/>
</Authorization>
</System. Web>
</Configuration>

Create a new Web. config In the subdirectory that requires authentication.

<? XML version = "1.0"?>
<Configuration>
<System. Web>
<Authorization>
<Deny users = "? "/>
</Authorization>
</System. Web>
</Configuration>

You can also specify relevant parameters in Web. config in the root path to control the Authentication mode.

Cookieless
Determine whether or not to use cookies and cookies.
. Usecookies
Specify that the cookie is always used on any device.
. Useuri
Never use cookies.
. Autodetect
If the device configuration file supports cookies, the cookie is specified; otherwise, the cookie is not used.
. Usedeviceprofile
If the browser supports cookies, the cookie is specified; otherwise, the cookie is not used.
For devices that support cookies, do not try to detect whether cookie support is enabled.
 
Defaurl URL
Defines the default URL used for redirection after authentication. The default value is "default. aspx ".
This attribute is very important when we directly open the logon page to log on.

Loginurl
Specify the logon URL to which the request is redirected if no valid authentication cookie is found. The default value is login. aspx.
 
Name
Specifies the HTTP cookie to be used for authentication. If you are running multiple applications on a server and each application requires
For a unique cookie, the cookie name must be configured in the web. config file of each application. The default value is ". aspxauth ".
 
Path
Specifies the path for the cookie sent by the application.
The default value is slash (/), because most browsers are case sensitive. If the path is case insensitive, the browser will not return the cookie.
 
Timeout
Specify the time before the cookie expires (in integer minutes ). Persistent cookie does not time out. The default value is "30" (30 minutes ).

For more information, see the msdn documentation.
MS-help: // Ms. msdnqtr. v80.chs/ms. msdn. v80/ms. netdevfx. v1_chs/dv_aspnetgenref/html/8163b8b5-ea6c-46c8-b5a9-c4c3de31c0b3.htm

<? XML version = "1.0"?>
<Configuration>
<System. Web>
<Compilation DEBUG = "true"/>
<Authentication mode = "forms">
<Forms loginurl = "~ /Logon. aspx "name =" myform "defaulturl =" index. aspx "timeout =" 10 ">
<Credentials passwordformat = "clear">
<User name = "username" Password = "password"/>
</Credentials>
</Forms>
</Authentication>
<Authorization>
<Allow users = "*"/>
</Authorization>
</System. Web>
</Configuration>

3. Verification Method

We can use one of the following four methods to write and redirect tickets. In fact, the first three methods are only encapsulation of the first 4th methods. 1 and 4 are recommended. Note that cookieless = "useuri" is not supported in the last three methods ".

// 1. Use the default authentication ticket
Formsauthentication. redirectfromloginpage ("username", true );

// 2. Use the default authentication ticket
Formsauthentication. setauthcookie ("username", false );
Response. Redirect (formsauthentication. getredirecturl ("username", false ));

// 3. Use the default authentication ticket
Response. Cookies. Add (formsauthentication. getauthcookie ("username", false ));
Response. Redirect (formsauthentication. getredirecturl ("username", false ));

// 4. Use a custom authentication ticket
Formsauthenticationticket ticket = new formsauthenticationticket (1, "username", datetime. Now, datetime. Now. addminutes (10), false, null );
Response. Cookies. Add (New httpcookie (formsauthentication. formscookiename, formsauthentication. Encrypt (ticket )));
Response. Redirect (formsauthentication. getredirecturl ("username", false ));

4. Custom ID type

The msdn document tells us that you can use custom principal and identity to replace genericprincipal and formsidentity in global. asax through the authenticate event. Because the authenticate event is triggered during the authenticaterequest event, we can create a user identity object (formsauthenticationeventargs. User) before other modules ).

MS-help: // Ms. msdnqtr. v80.chs/ms. msdn. v80/ms. netdevfx. v1_chs/cpref12/html/t_system_web_security_formsauthenticationeventhandler.htm

Class myprincipal: system. Security. Principal. iprincipal
{
//...
}

Class myidentity: system. Security. Principal. iidentity
{
//...
}

Public void formsauthentication_onauthenticate (Object sender, formsauthenticationeventargs ARGs)
{
If (formsauthentication. cookiessupported)
{
If (request. Cookies [formsauthentication. formscookiename]! = NULL)
{
Try
{
Formsauthenticationticket ticket = formsauthentication. decrypt (
Request. Cookies [formsauthentication. formscookiename]. value );
 
Args. User = new myprincipal (New myidentity (ticket), new string [0]);
}
Catch (exception E)
{
// Decrypt method failed.
}
}
}
Else
{
Throw new httpexception ("cookieless Forms authentication is not" +
"Supported for this application .");
}

}

Of course, there is another simple method.

If (! (Httpcontext. Current. User is myprincipal ))
{
Httpcontext. Current. User = new myprincipal (New myidentity (ticket), roles );
}

However, you only need to find a suitable time.

5. formsauthentication

Authenticate
Verify the user name and password against the creden stored in the application configuration file. This method can only verify the user name and password information stored in Web. config. In most cases, we will replace it with our own verification method.

Decrypt
Decrypts the encrypted string obtained from the cookie and creates the formsauthenticationticket object.

Encrypt
Encrypted formsauthenticationticket. The encrypted string is returned.

Getredirecturl
Returns the original request URL that causes redirection to the logon page. The getredirecturl method returns the URL specified by the returnurl variable name in the query string. For example, in the URL http://www.contoso.com/login.aspx? In returnurl = caller. aspx, The getredirecturl method returns caller. aspx. If the returnurl variable does not exist, the getredirecturl method returns the URL in the defaulturl attribute.

Redirectfromloginpage
Redirects authenticated users back to the original requested URL or defaurl URL.

Redirecttologinpage
Redirects the browser to the logon URL.

Renewticketifold
Conditional update of the issuance date and time, expiration date and time of formsauthenticationticket. Note that this method only returns the updated formsauthenticationticket object and does not write cookies.

Getauthcookie
Create an authentication cookie for the given user name and do not add it to the cookie set or URL of the response.

Setauthcookie
Create an authentication ticket for the provided user name and add it to the cookie set or URL of the response.

Signout
Delete the forms authentication ticket from the browser.

6. Ticket Custom Data Application

When using a custom ticket, we can add a userdata parameter. Using this parameter can bring unexpected benefits, such as storing the user's VIP level number and the permissions/role set. Of course, the length of cookie and URL parameters is limited, and the custom data cannot be too long.

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.