Extending Forms Validation

Source: Internet
Author: User
Tags datetime ticket account security
1. Use forms validation to store user custom information

Forms validation is an internal mechanism for storing user data in a cookie-based ticket FormsAuthenticationTicket because it is specially encrypted, so it should be more secure. and. NET, in addition to using this ticket to store their own information, but also left a place to give users the freedom of control, which is now to say userdata.

UserData can be used to store string types of information, and also enjoy the encryption protection provided by forms validation, when we need this information, we can also use a simple get method to take into account security and ease of use, to save some of the necessary sensitive information is useful.

Here's how to use UserData, and then give an example of what you actually use.

Create a new ticket that will be credited to the client IP in the ticket UserData
FormsAuthenticationTicket ticket=new FormsAuthenticationTicket (
1,username.text,datetime.now,datetime.now.addminutes (30),
false,request.userhostaddress);
Encrypt a ticket
String Authticket=formsauthentication.encrypt (ticket);
Save the encrypted ticket as a cookie
HttpCookie coo=new HttpCookie (formsauthentication.formscookiename,authticket);
Use a new cookie that has been added to the UserData
Response.Cookies.Add (COO);

The following is a method signature for one of the overloads of the FormsAuthenticationTicket constructor
Public FormsAuthenticationTicket (
int version,
String name,
DateTime IssueDate,
DateTime expiration,
BOOL Ispersistent,
String UserData
);

Parameters
Version
Version number.
Name
The user name associated with the authentication ticket.
IssueDate
The time the Cookie was issued.
Expiration
The expiration date of the Cookie.
Ispersistent
True if the Cookie is persistent, or false.
UserData
User-defined data that will be stored in a Cookie

The use of UserData is also very simple, FormsIdentity ticket property provides access to the current ticket, after the ticket can be used UserData property access to the saved information, of course, is decrypted.
((System.Web.Security.FormsIdentity) this. Context.User.Identity). Ticket.userdata


The following is a specific application.

Because forms validation is done through cookies, it needs to pass a ticket to work. Although the bill is encrypted and the contents are not visible, but this does not prevent people from using a fake identity to use the bill (like we can take someone else's key to open other people's locks), it is more common that users of different IP intercepted the ticket in the unsecured channel, and then use it to carry out some activities outside the security scope.

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

But what if you can't use SSL? We can determine whether the IP and ticket matching, if the IP is the first generation of the IP of the bill, then there is no problem, or destroy the bill.

To do this, we need to save the user's IP at the beginning of the process of logging on, so that the IP of the successor request will be verified as the original IP at any later request. The best place to save this sensitive IP is, of course, UserData, and the time to validate is when the AuthenticateRequest event occurs, that is, the application_ that is defined in Global.aspx.cs to handle this event The AuthenticateRequest method.

The example above has actually saved the user's IP to UserData, and the following is the process of validation.

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 ticket is invalidated by giving the GenericPrincipal empty genericidentity and roles, which forces the user to log on again. To test this method, you can change the condition to equal and see how it works:

This approach also has deficiencies, specifically:

1. Users who use the same proxy will have the same IP, so that this kind of fake attack cannot be prevented

2. If the user uses the dynamic IP, may cause the normal user to be we forcibly destroys the bill. But on the whole, this approach is more feasible.


2. Use security features with forms validation for safe operation.

PrincipalPermissionAttribute can work with forms validation for role-based or user-based security validation, which cannot be used at the assembly level. Its scope 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!");
}



Code generated #region the Web forms Designer
Override protected void OnInit (EventArgs e)
{
//
CodeGen: This call is required for the ASP.net Web forms Designer.
//
InitializeComponent ();
Base. OnInit (e);
}

<summary>
Designer supports required methods-do not use the Code editor to modify
The contents of this method.
</summary>
private void InitializeComponent ()
{
This. Load + = new System.EventHandler (this. Page_Load);
}
#endregion

}


Note that this example starts with the entire class, executes after the build, and if the current user is not Notus, an exception System.Security.SecurityException occurs, prompting the request for the principal permission to fail. Conversely, you can successfully access, and output two Hello world!, note that two. The current security scope is the entire class.

Next, we'll change the scope of the feature. Move the attribute declaration to the SayHello2 method, and then run after recompiling to find that the program throws the System.Security.SecurityException after it runs to the SayHello2 method. This means that the security scope is now narrowed to the method level.

This feature can be used to set user and role-based security protection for users and roles. The first parameter that it uses is the SecurityAction enumeration, which sets specific protection levels or measures. As we now use this demand, it is required 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 PrincipalPermission can be used declaratively to require that the current user be Bob and belong to the supervisor role.
[PrincipalPermissionAttribute (SecurityAction.Demand, name= "Bob",
Role= "Supervisor"] The following example shows how to request that the current user's identity is Bob, regardless of the role membership condition.
[PrincipalPermissionAttribute (SecurityAction.Demand, name= "Bob")]
The following example shows how to request only



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.