SoFunction
Updated on 2025-03-07

Forms authentication and role-based permission access

Main idea: Forms authentication is used to determine whether a user is legal. When the user is legal, the user can decide the page that can be accessed through the user's role.
Specific steps:
1. Create a website with the structure as follows:
Website root directory
Admin Directory          --->     Admin Directory
Pages that administrators can access
Users Directory          --->    Registered User Directory
Pages that can be accessed by registered users
Error directory          --->
---->                                                                                                                             �
---->                                                                                                                             �
---->                                                             �
---->                                                                                                                             �
2. The configuration is as follows:
Copy the codeThe code is as follows:

        <configuration>
            <>
<!--Set Forms Authentication-->
                <authentication mode="Forms">
                    <forms loginUrl="" name="" path="/" protection="All" timeout="30"/>
                </authentication>
                <authorization>
                    <allow users="*"/>
                </authorization>
            </>
        </configuration>

<!--Set the access permissions of the Admin directory-->
        <location path="Admin">
            <>
                <authorization>
                    <allow roles="Admin"/>
                    <deny users="?"/>
                </authorization>
            </>
        </location>
<!--Set the access permissions of the Users directory-->
        <location path="Users">
            <>
                <authorization>
                    <allow roles="User"/>
                    <deny users="?"/>
                </authorization>
            </>
        </location>

3. The login part code on the page is as follows:
Copy the codeThe code is as follows:

        protected void btnLogin_Click(object sender, EventArgs e)
        {    
//Forms authentication initialization
            ();
//Verify user input and get logged in user, txtName is the user name, txtPassword is the login password
            UserModel um = ValidUser((),());
            if (um != null)
            {
//Create an authentication ticket
             FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                                            ,
                                            ,
                                            (30),
                                            true,
//The character string to which the user belongs
                                            );
//Encrypted authentication tickets
             string hash = (ticket);
//Create a cookie to send to the client
             HttpCookie cookie = new HttpCookie(, hash);
             if ()
             {
                 = ;
             }
//Add prepared cookies to the response stream
             (cookie);

//Forward to the requested page
             ((,false));
            }
            else
            {
             ClientScriptManager csm = ;
((), "error_tip", "alert('Username or password is wrong! Authentication failed!');", true);
            }
        }    
//Verify the user
        private UserModel ValidUser(string name, string password)
        {
            return new UserService().Validate(name, password);
        }

4. Add a handler to the website, the common authentication code is as follows:
Copy the codeThe code is as follows:

//Remove the original User and add the role data to the user
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            if ( != null )
            {
                if ()
                {
                    if ( is FormsIdentity)
                    {
                        FormsIdentity id = (FormsIdentity);
                        FormsAuthenticationTicket ticket = ;

                        string userData = ;
                        string[] roles = (',');
//Rebuild and join the user-owned role array
                         = new GenericPrincipal(id, roles);
                    }
                }
            }
        }

5. The page loading code in the Admin directory is as follows:
Copy the codeThe code is as follows:

        protected void Page_Load(object sender, EventArgs e)
        {
//Determine whether the authenticated user has permission to access this page
            FormsIdentity id = (FormsIdentity);
//Determine whether the authenticated user is an Admin role
            if (!("Admin"))
            {
//Skip to the error prompt page with insufficient access permissions
                ("~/Error/", true);
            }
        }
// Code of the secure exit button
        protected void btnExit_Click(object sender, EventArgs e)
        {
//Cancel the bill
            ();
            ClientScriptManager csm = ;
(), "exit_tip", "alert('You have exited safely!');", true);
        }

6. The page loading code in the Users directory is as follows:
Copy the codeThe code is as follows:

        protected void Page_Load(object sender, EventArgs e)
        {
//Determine whether the authenticated user has permission to access this page
            FormsIdentity id = (FormsIdentity);
//Determine whether the authenticated user is a User role
            if (!("User"))
            {
//Skip to the error prompt page with insufficient access permissions
                ("~/Error/", true);
            }
        }
// Code of the secure exit button
        protected void btnExit_Click(object sender, EventArgs e)
        {
//Cancel the bill
            ();
            ClientScriptManager csm = ;
(), "exit_tip", "alert('You have exited safely!');", true);
        }

Test results:
data:
Suppose there are 3 users, as follows:
        ------------------------------------------
Username Password Role String
        ------------------------------------------
        sa        sa        Admin,User
        admin        admin        Admin
        user        user        User
        ------------------------------------------
test:
If you use admin to log in, you can only access the pages of the Admin directory;
If you use user to log in, you can only access the pages in the Users directory;
Log in with sa can access both the pages of the Admin directory and the pages of the Users directory.
Note: When testing, please click the safe exit button in time, otherwise it will affect the test results.