Using role-based forms validation in ASP.

Source: Internet
Author: User

Using role-based forms validation in ASP. Four steps:
1. Configure the system Web. config

<system.web>
<authentication mode= "Forms" >
<forms name= ". Yaocookies" Loginurl= "/duan/manage/login.aspx" protection= "All"
timeout= "path="/"/>
</authentication>
</system.web>

where <authentication mode= "Forms" > indicates that the application uses forms authentication.
1). The name in the <forms> tag indicates the HTTP Cookie to be used for authentication. By default, the value of name is. Aspxauth. After authenticating the user in this way, a FormsAuthenticationTicket type of authentication ticket is established with this user's information, and then the encryption is serialized to a string, Finally, this string is written to the client's name in the specified name of the cookie. Once this cookie is written to the client, the user will be sent to the server with a cookie once it is posted to the Web app, and the server will know that the user has been authenticated.

2). The loginurl in the <forms> tag specifies the URL to which the login will redirect the request if no valid authentication Cookie is found. The default value is default.aspx. Loginurl The specified page is used to verify the user's identity, generally this page provides user input user name and password, the user submitted by the program to verify the legality of the user according to their own needs (most of the situation is the user input information in the database with the user table to compare), if the authentication user is valid, Generates an authentication ticket corresponding to this user, writes to the client's cookie, and finally redirects the browser to the page requested by the user. Generally, the FormsAuthentication.RedirectFromLoginPage method is used to complete the generation of the authentication ticket, Write back a series of actions such as client, browser redirection and so on.

public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strcookiepath);

which
UserName: This is the user's logo, used to mark the user's unique identifier, not necessarily mapped to the user account name.
createPersistentCookie: Indicates whether a persistent Cookie is issued.
If it is not persistent cookie, The validity period of a cookie expiration property has the current time plus the timeout in Web. config, each time the page is requested, during the authentication process, it will determine if half of the validity period is expired, and if so, the expiration date of the cookie is updated; if persistent cookie,expiratio The n attribute is meaningless, when the validity of the authentication ticket is determined by the expires of the cookie, and the RedirectFromLoginPage method sets the 50-year validity period for the Expires attribute.
strCookiePath: Indicates the path of the cookie that will be generated to the client, and the path that is saved in the authentication ticket is used when the authentication ticket cookie is refreshed (this is also the path that generated the cookie), if there is no strCookiePath parameter, The setting of the Path property in Web. config is used.

As you can see, this method has only three parameters, and there are seven attributes for the authentication ticket, and the insufficient four parameters are:
Issuedate:cookie emitted time is derived from the current time,
Expiration: The expiration time is calculated from the current time and the timeout parameter in the <forms> tag. This parameter is meaningful for non-persistent cookies.
UserData: This property can be used by the application to write some user-defined data, this method does not use this property, but simply set this property to an empty string, note this property, in the following we will use to this property.
Version: The release number is automatically provided by the system.

After the RedirectFromLoginPage method generates an authentication ticket, the Formsauthentication.encrypt method is called, and the authentication ticket is encrypted to a string, which will be the string. Aspxauth is the value of a cookie for the name.
The other properties of this cookie are generated:
The Domain,path property is the exact province value, expires depending on the createPersistentCookie parameter, if the persistent cookie,expires is set to expire after 50, if the non-persistent Cookie,expires property is not set.
After the authentication cookie is generated, this cookie is added to the Response.Cookies and waits to be sent to the client.
Finally, the RedirectFromLoginPage method calls the Formsauthentication.getredirecturl method to obtain the page that the user originally requested, redirecting to this page.

3). The timeout and path in the <forms> tab are provided with the authentication ticket written to the cookie expiration time and the default path.

This is the process based on forms authentication, which completes the acknowledgement of the user's identity.

2. Create a Web. config file under a protected folder, such as manage, with content such as

<configuration>
<!--specify access to the entire manage directory--
<system.web>
<authorization>
           <!--multiple roles, separated--
<allow roles= "Admin,user"/>
<deny users= "*"/>
</authorization>
</system.web>

<!--can also control permissions on a page

<location path= "Announcelist.aspx" >
<system.web>
<authorization>
<allow roles= "admin"/>
<deny users= "*"/>
</authorization>
</system.web>
</location>

<location path= "Configinfo.aspx" >
<system.web>
<authorization>
<allow roles= "Users"/>
<deny users= "*"/>
</authorization>
</system.web>
</location>

-
</configuration>

Note: This configuration content can also be added to the system's Web. config file, note the join location:

........
</system.web>

<location path= "Manage/announcelist.aspx" >
<system.web>
<authorization>
<allow roles= "admin"/>
<deny users= "*"/>
</authorization>
</system.web>
</location>

</configuration>

The <allow> tag represents the allowed access, where the properties
1). Users: A comma-delimited list of user names that have been granted access to resources. The question mark (?) allows anonymous users, and an asterisk (*) allows all users.
2). Roles: A comma-delimited list of roles that have been granted access to resources.
3). Verbs: A comma-delimited list of HTTP transport methods that have been granted access to resources. The predicates registered to ASP. NET are, POST, and DEBUG.

The <deny> tag indicates that access is not allowed. The properties are the same as above.

At run time, the authorization module iterates through the <allow> and <deny> tags until it finds the first access rule that is appropriate for a particular user. It then allows or denies access to the URL resource based on whether the first access rule found is <allow> or <deny> rule. The default authentication rule in the Machine.config file is <allow users= "*"/>, so access is allowed by default unless otherwise configured.

So how do these user and roles get it? Here's a look at the details of the authorization process:

1). Once a user accesses the site, the login confirms the identity, and the cookie for the authentication ticket is also written to the client. After that, the user applies for the Web page again, and the cookie for the authentication ticket is sent to the server. On the service side, ASP. NET for each HTTP request is assigned a HttpApplication object to handle this request, after the Httpapplication.authenticaterequest event, the security module has established a user identity, that is, the user's identity on the web side has been established, this The identity is created solely by the cookie that the client sends back the authentication ticket.
2). User identity in the HttpContext.User attribute, the page can be page.context to get the HttpContext object associated with the page. For forms validation, the HttpContext.User property is an object of type GenericPrincipal, GenericPrincipal has only one public property identity, has a private m_role attribute, is string[] Type, which holds the array of roles that this user belongs to, and a public method IsInRole (string role) to determine whether the user belongs to a role.
Because the role is not provided in the cookie for the authentication ticket, it means that the forms authentication ticket does not provide the role information for this user, so for forms authentication, the GenericPrincipal user object that is obtained on the server is m_ The role attribute is always empty.
3). GenericPrincipal. The Identity property is an object of type formsidentity, which has a name attribute, which is the identifier of this user, and access authorization is to authenticate this attribute as user for authorization. FormsIdentity also has a property, which is the ticket property, which is the authentication ticket FormsAuthenticationTicket type, which is the authentication ticket previously written to the client by the server.
After the server obtains the authentication ticket FormsAuthenticationTicket object, it is not durable to see whether this authentication ticket is non-persistent authentication, Yes, you can update the cookie for this authentication ticket based on the validity period of the timeout attribute set in Web. config (to avoid compromising performance, update the cookie after more than half of the specified time. This can result in a loss of accuracy. Persistent cookies do not time out. )
4). Before the Httpapplication.resolverequestcache event, ASP. NET starts to obtain the user Request page, establishes the HttpHandler control point. This means that the Httpapplication.resolverequestcache event will be authenticated to the user's access rights, to see if the user or role has access to the page, and then to change the identity or role of the user within the lifetime of the request is meaningless.

The above is the whole process of forms verification, it can be seen that the forms validation is user-based, and does not provide direct support for role validation. The name attribute in the authentication ticket FormsAuthenticationTicket is a user ID, but there is also an attribute UserData, which can be used by the application to write custom data, and we can use this field to hold the information of role. So as to achieve the purpose of role-based verification.

3. Login Page

Login button
private void Button1_Click (object sender, System.EventArgs e)
{
The entity class Adminuservo corresponds to the Adminuser user table.
Adminuservo Adminuservo = new Adminuservo ();

Adminuservo.uname = UserName.Text.Trim ();
Adminuservo.upwd = UserPwd.Text.Trim ();
Adminuservo.lastip = HttpContext.Current.Request.UserHostAddress;
Adminuservo.lasttime = DateTime.Now;

BOOL flag = (new Logindao ()). CHK (Adminuservo);

if (flag)
{
You can use this sentence for non-role verification:
System.Web.Security.FormsAuthentication.SetAuthCookie (UserName.Text.Trim (), false);

                Create role verification information to write roles information to UserData
Setlogincookie (Adminuservo,adminuservo.roles.tolower ());

HttpContext.Current.Response.Redirect ("main.aspx");
}
Else
{
HttpContext.Current.Response.Write ("Login Failed");
}
}

Setlogincookie method
public static void Setlogincookie (Adminuservo u, string roles)
{
Establish an authentication ticket object
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,u.uname, DateTime.Now, DateTime.Now.AddMinutes (30 ), False,roles, "/");
Encrypt serialized validation ticket as String
String hashticket = Formsauthentication.encrypt (ticket);
HttpCookie Usercookie = new HttpCookie (Formsauthentication.formscookiename, Hashticket);
HTTPCONTEXT.CURRENT.RESPONSE.COOKIES.ADD (Usercookie);
}

FormsAuthenticationTicket parameter Description:
FormsAuthenticationTicket (
int version,  //is set to 1, and the version number is automatically provided by the system
String Name, //User ID, gets the user name associated with the authentication Cookie
DateTime issuedate,  //cookie time, set to DateTime.Now  
DateTime expiration, < Span style= "color: #339900;" >//Gets the date/time that the Cookie expires
bool Ispersistent, //is persistent (set as desired, if set to persistent, in the issue cookie, the expires setting of the Cookie must be set), or true if a persistent cookie has been issued. Otherwise, the authentication Cookie will be limited to the browser lifecycle.
String Userdata, //gets the application-defined string stored in the Cookie, with a comma-separated role string prepared above
String Cookiepath //returns the path where the Cookie was issued. Note that the path to the form is set to "/", which is consistent with the path where the cookie is issued, because this path is used to refresh the cookie. Because the form is case-sensitive, this is a safeguard that is taken to prevent inconsistencies in the case of URLs in the site.
);

4.global.asax.cs

protected void Application_AuthenticateRequest (Object sender, EventArgs e)
{
HttpApplication app = (HttpApplication) sender;
HttpContext CTX = App. Context; Gets the HttpContext object for this HTTP request
if (CTX. User! = null)
{
if (CTX. request.isauthenticated = = true)//authenticated generic user for role verification
{
System.Web.Security.FormsIdentity fi = (System.Web.Security.FormsIdentity) ctx. User.Identity;
System.Web.Security.FormsAuthenticationTicket ticket = fi. Ticket; Get an authentication ticket
String userData = Ticket. userdata;//recovering role information from the UserData
string[] roles = Userdata.split (', '); Turn role data into a string array to get the relevant role information
CTx. User = new System.Security.Principal.GenericPrincipal (FI, roles); So that the current user has role information
}
}
}

Note: If you use HttpModule, the code here should be added to the AuthenticateRequest event.

Using role-based forms validation in ASP.

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.