Forms authentication and role-based permission Control

Source: Internet
Author: User

Main Idea: Forms authentication is used to determine whether a user is valid. When the user is valid, the user's role determines the page that can be accessed.
Procedure:
1. Create a website with the following structure:
Website root directory
Admin directory ----> Administrator directory
Manager. aspx ----> pages accessible to administrators
Users directory ----> Register User directory
Welcome. aspx ----> pages accessible to registered users
Error directory ----> error prompt directory
Accesserror.htm ----> error prompt page
Default. aspx ----> default website page
Login. aspx ----> website logon page
Web. config ----> website configuration file
2. Configure web. config as follows:
<Configuration>
<System. Web>
<! -- Set forms authentication -->
<Authentication mode = "forms">
<Forms loginurl = "login. aspx" name = "mywebapp. apsxauth" Path = "/" Protection = "all" timeout = "30"/>
</Authentication>
<Authorization>
<Allow users = "*"/>
</Authorization>
</System. Web>
</Configuration>

<! -- Set the access permission for the Admin directory -->
<Location Path = "admin">
<System. Web>
<Authorization>
<Allow roles = "admin"/>
<Deny users = "? "/>
</Authorization>
</System. Web>
</Location>
<! -- Set the access permission for the users directory -->
<Location Path = "users">
<System. Web>
<Authorization>
<Allow roles = "user"/>
<Deny users = "? "/>
</Authorization>
</System. Web>
</Location>
3. log on to the login. ASPX page Code As follows:
Protected void btnlogin_click (Object sender, eventargs E)
{
// Forms authentication Initialization
Formsauthentication. initialize ();
// Verify the user input and obtain the login user. txtname indicates the user name, And txtpassword indicates the login password.
Usermodel um = validuser (txtname. Text. Trim (), txtpassword. Text. Trim ());
If (Um! = NULL)
{
// Create an authentication ticket
Formsauthenticationticket ticket = new formsauthenticationticket (1,
Um. Name,
Datetime. Now,
Datetime. Now. addminutes (30 ),
True,
Um. Roles, // role string to which the user belongs
Formsauthentication. formscookiepath );
// Encrypt the authentication ticket
String hash = formsauthentication. Encrypt (ticket );
// Create the cookie to be sent to the client
Httpcookie cookie = new httpcookie (formsauthentication. formscookiename, hash );
If (ticket. ispersistent)
{
Cookie. expires = ticket. expiration;
}
// Add the prepared cookie to the response stream
Response. Cookies. Add (cookie );

// Forwarded to the request page
Response. Redirect (formsauthentication. getredirecturl (UM. Name, false ));
}
Else
{
Clientscriptmanager CSM = This. Page. clientscript;
CSM. registerstartupscript (this. GetType (), "error_tip", "alert ('user name or Password error! Authentication failed! '); ", True );
}
}
// Verify the user
Private usermodel validuser (string name, string password)
{
Return new userservice (). Validate (name, password );
}
4. Add processing for the website Program Global. asax. The general authentication code is as follows:
// Transform the original user and add a role data to the user
Protected void application_authenticaterequest (Object sender, eventargs E)
{
If (httpcontext. Current. User! = NULL)
{
If (httpcontext. Current. User. Identity. isauthenticated)
{
If (httpcontext. Current. User. Identity is formsidentity)
{
Formsidentity id = (formsidentity) httpcontext. Current. User. identity;
Formsauthenticationticket ticket = ID. ticket;

String userdata = ticket. userdata;
String [] roles = userdata. Split (',');
// Re-create httpcontext. Current. User and add the user's role Array
Httpcontext. Current. User = new genericprincipal (ID, roles );
}
}
}
}
5. Load the following code on the manager. ASPX page in the Admin directory:
Protected void page_load (Object sender, eventargs E)
{
// Determine whether the authenticated user has the permission to access this page
Formsidentity id = (formsidentity) httpcontext. Current. User. identity;
// Determine whether the authenticated user is an admin role
If (! Id. Ticket. userdata. Contains ("admin "))
{
// Jump to the error prompt page with insufficient access permissions
Response. Redirect ("~ /Error/accesserror.htm ", true );
}
}
// Code of the secure exit button
Protected void btnexit_click (Object sender, eventargs E)
{
// Cancel the ticket
Formsauthentication. signout ();
Clientscriptmanager CSM = This. Page. clientscript;
CSM. registerstartupscript (this. GetType (), "exit_tip", "alert ('You have exited safely! '); ", True );
}
6. Load the following code on the welcome. ASPX page in the users directory:
Protected void page_load (Object sender, eventargs E)
{
// Determine whether the authenticated user has the permission to access this page
Formsidentity id = (formsidentity) httpcontext. Current. User. identity;
// Determine whether the authenticated user is a user role
If (! Id. Ticket. userdata. Contains ("user "))
{
// Jump to the error prompt page with insufficient access permissions
Response. Redirect ("~ /Error/accesserror.htm ", true );
}
}
// Code of the secure exit button
Protected void btnexit_click (Object sender, eventargs E)
{
// Cancel the ticket
Formsauthentication. signout ();
Clientscriptmanager CSM = This. Page. clientscript;
CSM. registerstartupscript (this. GetType (), "exit_tip", "alert ('You have exited safely! '); ", True );
}
Test results:
Data:
Assume that there are three users:
------------------------------------------
Username, password, and role string
------------------------------------------
Sa admin, user
Admin admin Admin
User user
------------------------------------------
Test:
If you use admin to log on, you can only access the manager. ASPX page of the Admin directory;
If you log on with a user, you can only access the welcome. ASPX page of the users directory;
Log On with SA to access the manager. ASPX page of the Admin directory and the welcome. ASPX page of the users directory.
Note: Click the secure exit button during testing. Otherwise, the test result will be affected.

 

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/Jelly_tracy/archive/2009/12/03/4932116.aspx

 

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.