Use Role-based authentication forms in Asp.net (1)

Source: Internet
Author: User
Tags http cookie

Role-based identity forms authentication in Asp.net is roughly divided into four steps
1. Configure the System File web. config

<System. Web>
<Authentication mode = "forms">
<Forms name = ". yaocookies" loginurl = "/Duan/manage/login. aspx" Protection = "all"
Timeout = "20" Path = "/"/>
</Authentication>
</System. Web>

<Forms> the name in the tag specifies the HTTP cookie to be used for authentication. By default, the name value is. aspxauth. After the user is verified in this way, a formsauthenticationticket authentication ticket is created based on the user information, and then encrypted and serialized into a string, finally, write the string to the cookie with the name specified by the client name. once the cookie is written to the client, the user will be sent to the server together with the cookie when accessing the web application again, and the server will know that the user has been verified.

<Forms> the loginurl In the tag indicates that a user without authentication will be automatically directed to the path pointed to by loginurl. if the authenticated user is valid, the authentication ticket corresponding to the user is generated, written to the cookie of the client, and the browser is redirected to the page of the user's initial request. system. web. security. formsauthentication. redirectfromloginpage () method for redirection.

<Forms> the timeout and path in the tag provide the authentication ticket write to the cookie expiration time and default path

2. Create a web. config file in a protected folder such as manage. The content is as follows:

<Configuration>
<! -- Specify the access permission for the entire manage directory -->
<System. Web>
<Authorization>
<! -- Separate multiple roles with commas (,) -->
<Allow roles = "Admin, user"/>
<Deny users = "*"/>
</Authorization>
</System. Web>

<! -- You can also control the permissions of 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: The configuration content can also be added to the web. config file of the system. Note the following:

........
</System. Web>

<Location Path = "manage/announcelist. aspx">
<System. Web>
<Authorization>
<Allow roles = "admin"/>
<Deny users = "*"/>
</Authorization>
</System. Web>
</Location>

</Configuration>

3. logon page

<Div style = "border-Right: # cccccc 1px solid; padding-Right: 5px; border-top: # cccccc 1px solid; padding-left: 4px; font-size: 13px; border-bottom-width: 1px; border-bottom-color: # cccccc; padding-bottom: 4px; border-left: # cccccc 1px solid; width: 98% "> // login button
Private void button#click (Object sender, system. eventargs E)
{
// The object class adminuservo corresponds to the adminuser User table.
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)
{
// This statement can be used for non-role authentication:
// System. Web. Security. formsauthentication. setauthcookie (username. Text. Trim (), false );

// Create role authentication information and write the role information to userdata
Setlogincookie (adminuservo, adminuservo. roles. tolower ());

Httpcontext. Current. response. Redirect ("Main. aspx ");
}
Else
{
Httpcontext. Current. response. Write ("Logon Failed ");
}
}
</Div>

<Div style = "border-Right: # cccccc 1px solid; padding-Right: 5px; border-top: # cccccc 1px solid; padding-left: 4px; font-size: 13px; border-bottom-width: 1px; border-bottom-color: # cccccc; padding-bottom: 4px; border-left: # cccccc 1px solid; width: 88.76%; height: 203px "> // setlogincookie Method
Public static void setlogincookie (adminuservo U, string roles)
{
// Create an identity authentication ticket object
Formsauthenticationticket ticket = new formsauthenticationticket (1, U. uname, datetime. Now, datetime. Now. addminutes (30), false, roles ,"/");
// The encrypted serialization verification ticket is a string
String hashticket = formsauthentication. Encrypt (ticket );
Httpcookie usercookie = new httpcookie (formsauthentication. formscookiename, hashticket );
Httpcontext. Current. response. Cookies. Add (usercookie );
}
</Div>
Formsauthenticationticket parameter description:
Formsauthenticationticket (
Int version, // set to 1. The version number is automatically provided by the system.
String name, // user ID to obtain the username associated with the authentication cookie
Datetime issuedate, // cookie sending time, set to datetime. Now
Datetime expiration, // get the cookie expiration date/time
Bool ispersistent, // whether the cookie is persistent (set as needed. If it is set to persistent, The expires setting of the cookie must be set when sending the cookie). If a persistent Cookie has been issued, returns true. Otherwise, the authentication cookie is restricted within the browser lifecycle.
String userdata, // obtain the application definition string stored in the cookie. Here, use the role string prepared above to separate it with commas (,).
String cookiepath // return the cookie sending path. Note: the path of the form is set to "/", which must be the same as the path for sending the cookie, because the path is used to refresh the cookie. The form is case-sensitive, which is a protection measure to prevent the URL in the site from being case-insensitive.
);

4. Global. asax. CS

<Div style = "border-Right: # cccccc 1px solid; padding-Right: 5px; border-top: # cccccc 1px solid; padding-left: 4px; font-size: 13px; border-bottom-width: 1px; border-bottom-color: # cccccc; padding-bottom: 4px; border-left: # cccccc 1px solid; width: 98% "> protected void application_authenticaterequest (Object sender, eventargs E)
{
Httpapplication APP = (httpapplication) sender;
Httpcontext CTX = app. Context; // obtain the httpcontext object of this HTTP Request
If (CTX. User! = NULL)
{
If (CTX. Request. isauthenticated = true) // a verified general user can perform role verification.
{
System. Web. Security. formsidentity Fi = (system. Web. Security. formsidentity) CTX. User. identity;
System. Web. Security. formsauthenticationticket ticket = Fi. Ticket; // get the authentication ticket
String userdata = ticket. userdata; // restore role information from userdata
String [] roles = userdata. Split (','); // convert the role data into a string array to obtain the relevant role information.
CTX. User = new system. Security. Principal. genericprincipal (FI, roles); // The current user has the role information.
}
}
} </Div>
NOTE: If httpmodule is used, the code should be added to the authenticaterequest event.

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/Python/archive/2008/11/11/3277230.aspx

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.