1
This is the code in global. ascx.
2 protected void application_authenticaterequest (Object sender, eventargs E)
3 {
4 If (httpcontext. Current. User! = NULL) // if the current HTTP information contains user information
5 {
6 if (httpcontext. Current. User. Identity. isauthenticated) // if the identity of the current user has been verified
7 {
8 If (httpcontext. Current. User. Identity is formsidentity)
9 {
10 // if the current user identity is formsidentity, that is, Form Verification class, this class has an attribute that can access the verification ticket of the current user
11 formsidentity Fi = (formsidentity) httpcontext. Current. User. Identity; // create a formsidentity class and use it to access the verification ticket of the current user
12 // obtain the user's verification ticket
13 formsauthenticationticket ticket = Fi. ticket;
14 // obtain user data, that is, role data, from the verification ticket
15 string userdata = ticket. userdata;
16 // use user data into a role Array
17 string [] roles = userdata. Split (',');
18 // rewrite the current user information, that is, add the role information to the user information.
19 httpcontext. Current. User = new genericprincipal (FI, roles );
20
21}
22}
23}
24}
25
Here is the login module code
1 protected void lblogin_click (Object sender, eventargs E)
2 {
3 string uname = This. textbox1.text;
4 string Pwd = This. textbox2.text;
5 string roles = NULL;
6 bool check = roledata. rolecontrol (uname, PWD, out roles );
7if (check)
8 {
9 // create a new verification ticket formsauthenticationticket
10 formsauthenticationticket ticket = new formsauthenticationticket (
111, // ticket version number
12 uname, // User Name
13datetime. Now, // cookie generation time
14datetime. Now. addminutes (20), // cookie Validity Period
15 false, // whether the cookie exists permanently
16 roles); // User Role data read from the database
17
18 // encrypt the verification ticket
19 string hashticket = formsauthentication. Encrypt (ticket );
20
21 // set the verification ticket cookie. The first parameter is the cookie name, and the second parameter is the cookie value, that is, the encrypted ticket.
22 httpcookie cookie = new httpcookie (formsauthentication. formscookiename, hashticket );
23 // adding the cookie to the response object occurs to the client
24 // get the requested URL
25response. Cookies. Add (cookie );
26 string requesturl = formsauthentication. getredirecturl (formsauthentication. formscookiename, false );
27
28 // do not use the formsauthentication. redirectfromloginpage method, because this method will overwrite the cookie
29 // redirect to the requested URL
30if (requesturl! = NULL)
31 {
32response. Redirect (requesturl );
33}
34 else
35 {
36response. Redirect ("index. aspx ");
37}
38}
39 else
40 {
41this. lbcheck. Text = "the user name or password is incorrect. Please try again! ";
42this. lbcheck. Visible = true;
43}
44}
45}