Main idea: Forms authentication is used to determine whether a legitimate user, when the user is legitimate, and then through the user's role to determine the page can be accessed.
Specific steps:
1, create a website, the structure is as follows:
Site root directory
Admin directory----> Admin directory
manager.aspx----> Admin can access the page
Users directory----> registered user Directory
welcome.aspx----> Registered pages that users can access
Error directory----> wrong hints directory
accesserror.htm----> Access Error Tips page
Default.aspx----> website default page
Login.aspx----> Website Login page
Web.config----> Web site configuration file
2, the configuration web.config as follows:
Copy Code code as follows:
<configuration>
<system.web>
<!--set Forms authentication-->
<authentication mode= "Forms" >
<forms loginurl= "Login.aspx" name= "Mywebapp.apsxauth" path= "/" protection= "All" timeout= "/>"
</authentication>
<authorization>
<allow users= "*"/>
</authorization>
</system.web>
</configuration>
<!--set access permissions for the admin directory-->
<location path= "Admin" >
<system.web>
<authorization>
<allow roles= "Admin"/>
<deny users= "?" />
</authorization>
</system.web>
</location>
<!--set access permissions for the users directory-->
<location path= "Users" >
<system.web>
<authorization>
<allow roles= "User"/>
<deny users= "?" />
</authorization>
</system.web>
</location>
3, in the Login.aspx page login part of the code is as follows:
Copy Code code as follows:
protected void Btnlogin_click (object sender, EventArgs e)
{
Forms authentication Initialization
Formsauthentication.initialize ();
Verify user input and get logged in user, txtname is user name, Txtpassword is 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,//the role string to which the user belongs
Formsauthentication.formscookiepath);
Encrypted authentication ticket
String hash = Formsauthentication.encrypt (ticket);
Create a cookie to send to the client
HttpCookie cookies = new HttpCookie (formsauthentication.formscookiename, hash);
if (ticket. Ispersistent)
{
Cookie. Expires = ticket. expiration;
}
Add the prepared cookie to the response stream
RESPONSE.COOKIES.ADD (cookie);
Forward to the requested page
Response.Redirect (Formsauthentication.getredirecturl (um. Name,false));
}
Else
{
ClientScriptManager CSM = this. Page.clientscript;
Csm. RegisterStartupScript (this. GetType (), "Error_tip", "alert (' Username or password is wrong!") Authentication failed! '); ", true);
}
}
Verifying users
Private Usermodel ValidUser (string name, string password)
{
return new UserService (). Validate (name, password);
}
4, add the handler global.asax to the website, where the common authentication code is as follows:
Copy Code code as follows:
Transform the original user to add a user-owned role data
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 (', ');
Rebuilding HttpContext.Current.User, adding a user-owned array of roles
HttpContext.Current.User = new GenericPrincipal (ID, roles);
}
}
}
}
5, in the Admin directory manager.aspx page load code as follows:
Copy Code code as follows:
protected void Page_Load (object sender, EventArgs e)
{
Determine if the authenticated user has permission to access this page
FormsIdentity id = (formsidentity) HttpContext.Current.User.Identity;
To determine whether an authenticated user is an admin role
if (!id. Ticket.UserData.Contains ("Admin"))
{
Skip to Error prompt page with insufficient access rights
Response.Redirect ("~/error/accesserror.htm", true);
}
}
Code for Safe Exit button
protected void Btnexit_click (object sender, EventArgs e)
{
Cancellation of bills
FormsAuthentication.SignOut ();
ClientScriptManager CSM = this. Page.clientscript;
Csm. RegisterStartupScript (this. GetType (), "Exit_tip", "Alert" (' You have safely quit! '); ", true);
}
6, in the Users directory welcome.aspx page load code as follows:
Copy Code code as follows:
protected void Page_Load (object sender, EventArgs e)
{
Determine if the authenticated user has permission to access this page
FormsIdentity id = (formsidentity) HttpContext.Current.User.Identity;
To determine whether an authenticated user is a users role
if (!id. Ticket.UserData.Contains ("User"))
{
Skip to Error prompt page with insufficient access rights
Response.Redirect ("~/error/accesserror.htm", true);
}
}
Code for Safe Exit button
protected void Btnexit_click (object sender, EventArgs e)
{
Cancellation of bills
FormsAuthentication.SignOut ();
ClientScriptManager CSM = this. Page.clientscript;
Csm. RegisterStartupScript (this. GetType (), "Exit_tip", "Alert" (' You have safely quit! '); ", true);
}
Test results:
Data:
Suppose there are 3 users, as follows:
------------------------------------------
User name Password role string
------------------------------------------
SA sa Admin,user
Admin Admin Admin
User User User
------------------------------------------
Test:
If you use admin login, you can only access the Manager.aspx page of the admin directory;
If you log on using user, you can only access the Welcome.aspx page of the users directory;
With SA login, you can access both the Manager.aspx page of the admin directory and the welcome.aspx page of the users directory.
Note: When testing, pay attention to the safe exit button in time, otherwise affect the test results.