Asp.net form-based authentication

Source: Internet
Author: User
Tags form post http cookie md5 digest send cookies
Form-based authentication

// Login page

Protected void button#click (Object sender, eventargs E)
{
String username = "tsuser ";
String userpwd = "resust ";
String roles = "Adminstrator ";

// Generate the verification ticket object.
Formsauthenticationticket authticket = new formsauthenticationticket (
1,
Username,
Datetime. Now, datetime. Now. addminutes (1 ),
False,
Roles );

// Encrypted verification ticket
String encrytedticket = formsauthentication. Encrypt (authticket );
// Generate the cookie object.
// Formsauthentication. formscookiename get <authentication>
// The name value in the configuration section is used as the cookie name.
Httpcookie authcookie = new httpcookie (formsauthentication. formscookiename,
Encrytedticket );
Response. Cookies. Add (authcookie );

// Jump to the user's initial request page.
String DDD = formsauthentication. getredirecturl (username, false );

Response. Redirect ("webform1.aspx ");
// Server. Transfer ("webform1.aspx ");
}

// Add using system. Security. Principal; namespace in global. asax
Protected void application_authenticaterequest (Object sender, eventargs E)
{
// Obtain the role of a user.
String cookiename = formsauthentication. formscookiename; // obtain the cookie name from the verification ticket.

// Obtain the cookie.
Httpcookie authcookie = context. Request. Cookies [cookiename];

If (null = authcookie)
{
Return;
}
Formsauthenticationticket authticket = NULL;

// Obtain the verification ticket.
Authticket = formsauthentication. decrypt (authcookie. value );

If (null = authticket)
{
Return;
}

// The userdata of the authentication ticket stores the user role information.
// Userdata stores user-defined information. This is used to store user roles.
String [] roles = authticket. userdata. Split (New char [] {','});

Formsidentity id = new formsidentity (authticket );

Genericprincipal principal = new genericprincipal (ID, roles );

// Assign the generated verification ticket information and role information to the current user.
Context. User = principal;
}

// Directly go to the home page without verification. The default. aspx page is returned */

// It can also be determined on the New Page

If (! Httpcontext. Current. User. isinrole ("Adminstrator "))
{
Response. Redirect ("default. aspx ");
}

/* // Add in Web. config
<Authentication mode = "forms">
<Forms name = "mywebapp. aspxauth"
Loginurl = "default. aspx"
Protection = "all"
Path = "/"/>
</Authentication>
<! -- Set access to the local directory. Access fails if the ticket is not verified
-->
<Authorization>
<! -- Order and case are important below -->
<Allow roles = "Adminstrator"/>
<Deny users = "*"/>
</Authorization>

Form-based authentication is an ASP. NET authentication service that enables applicationsProgramYou can provide your own logon user interface and verify your creden. ASP. NET authenticates users, redirects unauthenticated users to the logon page, and performs all necessary cookie management. This authentication is a popular method used by many websites.

The application must be configured to use form-based authentication by setting<Authentication>SetFormsAnd reject anonymous user access. The following example shows how to complete this operation in the web. config file of the application:

<Configuration> <system. Web> <Authentication mode = "forms"/> <authorization> <deny users = "? "/> </Authorization> </system. Web> </configuration>

The Administrator uses form-based authentication to configure the name of the cookie to be used, the protection type, the URL used for Logon pages, the validity period of the cookie, and the path used for the sent cookie. The following table shows<Forms>Valid attribute of an element, which is shown in the following example<Authentication>Child element of the element:

 
<Authentication mode = "forms"> <forms name = ". aspxcookiedemo "loginurl =" login. aspx "defaulturl =" default. aspx "Protection =" all "timeout =" 30 "Path ="/"requiressl =" false "slidingexpiration =" true "enablecrossappredirects =" false "cookieless =" usedeviceprofile "Domain =" "> <! -- Protection = "[All | none | encryption | validation]" --> <! -- Cookieless = "[useuri | usecookies | autodetect | usedeviceprofile]" --> </Forms> </authentication>
Attribute Description
Cookieless ASP. NET 2.0 Forms authentication can store forms authentication tickets in cookies or URLs without cookies.UsedeviceprofileThe default value indicates that ASP. NET determines the location of the storage ticket based on the pre-calculated browser configuration file.AutodetectEnables ASP. NET to dynamically determine whether the browser supports cookies.UseuriAndUsecookiesEnforce no-Cookie tickets and no-Cookie tickets respectively.
Defaurl URL Specifies the default URL to which the request will be redirected after successful logon. This value is used if the Redirection URL is unavailable for Forms authentication after logon.
Domain SpecifyHttpcookieOfDomainAttribute Value. Explicitly setting this attribute allows applications to share the same cookie, provided that these applications share a public part of a DNS namespace (for example, ifDomainIf the attribute is set to "contoso.com", appa.contoso.com and appb.contoso.com can share a cookie ).
Enablecrossappredirects In ASP. NET 2.0, Forms authentication allows you to pass Forms authentication tickets between applications in the form of query string variables or form post variables. Set this attribute to true to enableFormsauthenticationmoduleThe ticket can be extracted from the query string or form post variable.
Loginurl Specifies the URL to which requests from unauthenticated users will be redirected. The URL can be on the same computer or remote computer. If it is on a remote computerMachinekeyIn the configuration elementDecryptionkeyAndValidationkeyAll attributes must use the same value.
Name The name of the HTTP cookie used for authentication. NOTE: If multiple applications need to use the form-based authentication service on one computer, and each application wants the application to isolate Forms authentication cookies, each application should be configured with a unique cookie value. To avoid generating dependencies in URLs, Asp. net also uses "/" as the path value to send these cookies back to each application on the site.
Path The path of the cookie to be sent. The default value is "/" to avoid difficulties caused by mismatch between upper and lower case characters in the path, because the browser is case sensitive when returning cookies. Applications in the shared server environment should use this command to maintain private cookies. (They can also use the API to specify a path at runtime to send cookies .)
Protection The method used to protect cookie data. Valid values:

  • All: Both data authentication and encryption are used to protect cookies. Verify the configured dataAlgorithmIs based on<Machinekey>Element. If the key is long enough (48 characters), AES encryption is used by default.AllIs the default (and recommended) value.
  • None: Used to use cookies only for websites with low security requirements. Encryption and verification can be disabled. Although you need to be cautious when using cookies in this way, this setting provides the best performance for any method that uses. NET Framework for personalized settings.
  • Encryption: Uses AES, tripledes, or des to encrypt cookies, but does not perform data verification on cookies. These cookies are vulnerable to carefully selected plain text attacks.
  • Validation: Do not encrypt the cookie content, but verify that the cookie data has not been changed during transmission. To create a cookie, verify that the key is connected to the cookie data in the buffer, calculate the Mac and append it to the output cookie.
Requiressl If it is set to true, Forms authentication sets the Security bit of the forms authentication cookie. Compatible browsers only send cookies back to ASP. NET over SSL connections. Note: This setting is invalid if no cookie Forms authentication is used.
Slidingexpiration If it is set to true, Forms authentication regularly updates the lifetime of Forms authentication tickets. This operation is performed regardless of whether the ticket is contained in a cookie or in a URL without a cookie.
Timeout Time (in the unit of integer minutes). After the time, the cookie will expire. The default value is30. The timeout attribute is an adjustable value. It is calculated from the time when the last request is received.NExpired in minutes. To avoid negative impact on performance, and to avoid multiple browser warnings from applications that have opened the cookie warning, the cookie is updated when the timeout time is over half. (This means that loss of precision may occur in some cases .)

After the application is configured, you must provide a logon page. The following example shows a simple logon page. The default. aspx page is required for this example. Unauthenticated requests are redirected to the logon page (login. aspx), which displays a simple form prompting you to enter your email address and password. (Use username = "someone@www.contoso.com" and Password = "password" as creden .)

After the creden are verified, the application calls the following:


C # VB
 formsauthentication. redirectfromloginpage (useremail. value, persistcookie. checked); 
 formsauthentication. redirectfromloginpage (useremail. value, persistcookie. checked) 

This redirects the user back to the original requested URL. Applications that do not want to execute redirection can callFormsauthentication. getauthcookieTo retrieve the cookie value. You can also callFormsauthentication. setauthcookieAppend the correctly encrypted cookie to the output response. These methods are useful for applications that provide logon user interfaces embedded in pages, or applications that want to control more locations to which users are redirected.

The authentication cookie can be either temporary or permanent ("persistent. Temporary cookies are only maintained during the current browser session. When the browser is closed, the cookie will be lost. The permanent cookie is saved by the browser and sent back during each session of the browser, unless the user explicitly deletes the cookie or the cookie ends. Temporary cookie and permanent cookieTimeoutConfirm the configuration attributes. This is slightly changed in behavior compared with earlier versions of ASP. NET. in earlier versions, permanent cookie survival is 50 years. In ASP. NET 2.0, the expiration date of temporary and permanent cookies is set to the current time plusTimeoutConfiguration Attribute Value.

C # forms-based/cookie Authentication


Authentication cookie used by Forms authenticationSystem. Web. Security. formsauthenticationticketThe serialization version of the class. The information includes the user name (but no password), the forms authentication version used, the date on which the cookie is sent, and the optional application-specific data fields.

UseFormsauthentication. signoutMethod, ApplicationCodeYou can cancel or remove authentication cookies. This will remove the authentication cookie, whether it is temporary or permanent.

You can also use the list of valid creden: configured for the form-based authentication service, as shown in the following example:

 
<Authentication> <credentials passwordformat = "sha1"> <user name = "Mary" Password = "94f85995c7425eec546c321821aa4beca9a3e2b1"/> <user name = "John" Password = "guest"/> /Credentials> </authentication>

You can also useFormsauthentication. hashpasswordforstoringinconfigfile (string password, string passwordformat)The hash representation of the password generated by the API. This method supports using sha1 or MD5 to generate hash values. Then, the application can callFormsauthentication. AuthenticateAnd provide the user name and password, ASP. NET will verify the credential. AccordingPasswordformatThe following values of attributes. credenmd5 can be stored in plain text or sha1 or MD5:

hash type description
clear the password is stored in plaintext
sha1 the password is stored as the sha1 digest
MD5 the password is stored as an MD5 Digest
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.