Asp.net extension forms Verification

Source: Internet
Author: User

1. Use Forms verification to store user-defined information

The internal mechanism of Forms authentication is to encrypt user data and save it in a cookie-based ticket formsauthenticationticket. Because it is specially encrypted, it should be safer. In addition to using this bill to store your own information,. Net also leaves a place for the user to control freely. This is the userdata to be mentioned now.

Userdata can be used to store string-type information and enjoy the encryption protection provided by Forms authentication. When we need this information, we can also get it through a simple get method, taking into account the security and ease of use, it is useful to save some necessary sensitive information.

The following shows how to use userdata. An example is provided.

 

// Create a new ticket and record the Client IP address to ticket's userdata

Formsauthenticationticket ticket = new formsauthenticationticket (

1, username. Text, datetime. Now, datetime. Now. addminutes (30 ),

False, request. userhostaddress );

// Encrypt the ticket

String authticket = formsauthentication. Encrypt (ticket );

// Save the encrypted ticket as a cookie

Httpcookie coo = new httpcookie (formsauthentication. formscookiename, authticket );

// Use the new cookie with userdata added

Response. Cookies. Add (COO );

 

The following is the method signature of one of the reloads of the formsauthenticationticket constructor.

Public formsauthenticationticket (

Int version,

String name,

Datetime issuedate,

Datetime expiration,

Bool ispersistent,

String userdata

);

 

Parameters

Version

Version number.

Name

The username associated with the authentication ticket.

Issuedate

The time when the cookie is sent.

Expiration

The expiration date of the cookie.

Ispersistent

If the cookie is persistent, it is true; otherwise, it is false.

Userdata

User-Defined data stored in cookies

 

Using userdata is also very simple. The ticket attribute of formsidentity provides access to the current ticket. After obtaining the ticket, you can use the userdata attribute to access the saved information, which is decrypted.

(System. Web. Security. formsidentity) This. Context. User. Identity). Ticket. userdata

 

The following is a specific application.

Because Forms authentication is carried out through cookies, it needs to pass a ticket for work. Although the ticket is encrypted and the content is invisible, it cannot prevent others from using the ticket with a fake identity (just as we can use others' keys to unlock others' locks ), it is common that users of different IP addresses intercept the ticket through insecure channels and then use it for activities outside the security scope.

One way to solve this problem is to use SSL to transmit information.

But what if I cannot use SSL? We can determine whether the IP address matches the ticket. If the requested IP address is the IP address that generates the ticket for the first time, there is no problem; otherwise, the ticket will be destroyed.

Therefore, we need to save the user's IP address when processing the login at the beginning, so that we can verify whether the IP address of the subsequent request is the same as the initial IP Address at any time in future requests. The best place to store this sensitive IP address is userdata, and the verification time is when the authenticaterequest event occurs, that is, global. aspx. CS defines the application_authenticaterequest method for processing this event.

The preceding example actually saves the user IP address to userdata. The verification process is as follows.

If (this. Request. isauthenticated)

{

If (system. Web. Security. formsidentity) This. Context. User. Identity). Ticket. userdata! = This. Request. userhostaddress)

{

System. Security. Principal. genericidentity gi = new system. Security. Principal. genericidentity ("","");

String [] rolesi = {};

System. Security. Principal. genericprincipal GPI = new system. Security. Principal. genericprincipal (GI, rolesi );

This. Context. User = GPI;

}

}

The genericidentity and roles empty for genericprincipal invalidate the ticket, which forces the user to log on again. To test this method, you can first change the conditions to equal, to see how it works :)

This method also has shortcomings, specifically:

1. users using the same proxy will have the same IP address, so they cannot prevent such counterfeit attacks.

2. If the user uses a dynamic IP address, the normal user may be forcibly destroyed by us. But in general, this method is quite feasible.

2. Use security features with forms authentication for security operations.

Principalpermissionattribute can be used with forms authentication for role-based or user-based security authentication. This feature cannot be usedProgramSet level. It can be a class or a specific method. Let's look at a simple example.

[Principalpermission (securityaction. Demand, user = "notus")]

Public class test: basepage

{

Private void page_load (Object sender, system. eventargs E)

{

Try

{

This. sayhello ();

This. sayhello2 ();

}

Catch (exception ex)

{

Response. Write (ex. tostring ());

}

}

 

Private void sayhello ()

{

Response. Write ("Hello world! ");

}

 

Private void sayhello2 ()

{

Response. Write ("Hello principalpermissionattribute! ");

}

 

# Generated by region web Form DesignerCode

Override protected void oninit (eventargs E)

{

//

// Codegen: This call is required by the ASP. NET web form designer.

//

Initializecomponent ();

Base. oninit (E );

}

 

/// <Summary>

/// The designer supports the required methods-do not use the code editor to modify

/// Content of this method.

/// </Summary>

Private void initializecomponent ()

{

This. Load + = new system. eventhandler (this. page_load );

}

# Endregion

}

 

Note that this example applies to the entire class at the beginning. It is generated and executed. If the current user is not notus, an exception system. Security. securityexception will occur, prompting that the request for the subject permission fails. Otherwise, you can access the service smoothly and output two Hello world !, Note that there are two. The current security scope is the entire class.

Next, let's change the scope of the feature. Move the feature declaration to the sayhello2 method and run it after re-compilation. Then, the system. Security. securityexception is thrown after the program runs to the sayhello2 method. This shows that the scope of security is now reduced to the method level.

This feature allows you to set user and role for user and role-based security protection. In addition, the first parameter used is the securityaction enumeration, which sets a specific protection level or measure. The demand we use now requires that all advanced callers in the call stack have been granted the permissions specified by the current permission object.

The following is an example from msdn:

Example

 

The following example shows how to use principalpermission to claim that the current user is Bob and belongs to the supervisor role.

[Principalpermissionattribute (securityaction. Demand, name = "Bob ",

Role = "supervisor")] the following example shows how to require the identity of the current user to be Bob, which is irrelevant to the role Member conditions.

[Principalpermissionattribute (securityaction. Demand, name = "Bob")]

The following example shows how to verify the identity of a user only.

[Principalpermissionattribute (securityaction. Demand, Authenticated = true)]

 

Here, the user and role can be integrated with forms verification. Accordingly, we can use principalpermissionattribute in some important classes or methods, to arm your program to the home.

 

In fact, this feature has far more functions than this. For more details, refer to msdn.

 


 

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.