Asp.net Forms authentication and role-based access

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: Copy codeThe Code is 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. the logon code on the login. aspx page is as follows:Copy codeThe Code is 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 the processing program Global. asax to the website. The general authentication code is as follows:Copy codeThe 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:Copy codeThe Code is as follows: 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:Copy codeThe Code is as follows: 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
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.

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.