当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net Forms身份验证和基于角色的权限访问

asp.net Forms身份验证和基于角色的权限访问

2017年12月12日  | 移动技术网IT编程  | 我要评论

卫星最新参数,赣南脐橙,女排精英赛

主要思想:forms身份验证用来判断是否合法用户,当用户合法后,再通过用户的角色决定能访问的页面。
具体步骤:
    1、创建一个网站,结构如下:
        网站根目录
            admin目录            ---->    管理员目录
                manager.aspx        ---->    管理员可以访问的页面
            users目录            ---->    注册用户目录
                welcome.aspx        ---->    注册用户可以访问的页面
            error目录            ---->    错误提示目录
                accesserror.htm        ---->    访问错误的提示页面
            default.aspx            ---->    网站默认页面
            login.aspx            ---->    网站登录页面
            web.config            ---->    网站配置文件
    2、配置web.config如下:
复制代码 代码如下:

        <configuration>
            <system.web>
                <!--设置forms身份验证-->
                <authentication mode="forms">
                    <forms loginurl="login.aspx" name="mywebapp.apsxauth" path="/" protection="all" timeout="30"/>
                </authentication>
                <authorization>
                    <allow users="*"/>
                </authorization>
            </system.web>
        </configuration>

        <!--设置admin目录的访问权限-->
        <location path="admin">
            <system.web>
                <authorization>
                    <allow roles="admin"/>
                    <deny users="?"/>
                </authorization>
            </system.web>
        </location>
        <!--设置users目录的访问权限-->
        <location path="users">
            <system.web>
                <authorization>
                    <allow roles="user"/>
                    <deny users="?"/>
                </authorization>
            </system.web>
        </location>

    3、在login.aspx页面的登录部分代码如下:
复制代码 代码如下:

        protected void btnlogin_click(object sender, eventargs e)
        {    
            //forms身份验证初始化
            formsauthentication.initialize();
            //验证用户输入并得到登录用户,txtname是用户名称,txtpassword是登录密码
            usermodel um = validuser(txtname.text.trim(),txtpassword.text.trim());
            if (um != null)
            {
             //创建身份验证票据
             formsauthenticationticket ticket = new formsauthenticationticket(1,
                                            um.name,
                                            datetime.now,
                                            datetime.now.addminutes(30),
                                            true,
                                            um.roles,//用户所属的角色字符串
                                            formsauthentication.formscookiepath);
             //加密身份验证票据
             string hash = formsauthentication.encrypt(ticket);
             //创建要发送到客户端的cookie
             httpcookie cookie = new httpcookie(formsauthentication.formscookiename, hash);
             if (ticket.ispersistent)
             {
                cookie.expires = ticket.expiration;
             }
             //把准备好的cookie加入到响应流中
             response.cookies.add(cookie);

             //转发到请求的页面
             response.redirect(formsauthentication.getredirecturl(um.name,false));
            }
            else
            {
             clientscriptmanager csm = this.page.clientscript;
             csm.registerstartupscript(this.gettype(), "error_tip", "alert('用户名或密码错误!身份验证失败!');", true);
            }
        }    
        //验证用户
        private usermodel validuser(string name, string password)
        {
            return new userservice().validate(name, password);
        }

    4、给网站添加处理程序global.asax,其中通用身份验证代码如下:
复制代码 代码如下:

        //改造原来的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(',');
                        //重建httpcontext.current.user,加入用户拥有的角色数组
                        httpcontext.current.user = new genericprincipal(id, roles);
                    }
                }
            }
        }

    5、在admin目录中manager.aspx页面加载代码如下:
复制代码 代码如下:

        protected void page_load(object sender, eventargs e)
        {
            //判断通过身份验证的用户是否有权限访问本页面
            formsidentity id = (formsidentity)httpcontext.current.user.identity;
            //判断通过身份验证的用户是否是admin角色
            if (!id.ticket.userdata.contains("admin"))
            {
                //跳转到访问权限不够的错误提示页面
                response.redirect("~/error/accesserror.htm", true);
            }
        }
        //安全退出按钮的代码
        protected void btnexit_click(object sender, eventargs e)
        {
            //注销票据
            formsauthentication.signout();
            clientscriptmanager csm = this.page.clientscript;
            csm.registerstartupscript(this.gettype(), "exit_tip", "alert('您已经安全退出了!');", true);
        }

    6、在users目录中welcome.aspx页面加载代码如下:
复制代码 代码如下:

        protected void page_load(object sender, eventargs e)
        {
            //判断通过身份验证的用户是否有权限访问本页面
            formsidentity id = (formsidentity)httpcontext.current.user.identity;
            //判断通过身份验证的用户是否是user角色
            if (!id.ticket.userdata.contains("user"))
            {
                //跳转到访问权限不够的错误提示页面
                response.redirect("~/error/accesserror.htm", true);
            }
        }
        //安全退出按钮的代码
        protected void btnexit_click(object sender, eventargs e)
        {
            //注销票据
            formsauthentication.signout();
            clientscriptmanager csm = this.page.clientscript;
            csm.registerstartupscript(this.gettype(), "exit_tip", "alert('您已经安全退出了!');", true);
        }

测试结果:
    数据:
        假设有3个用户,如下:
        ------------------------------------------
        用户名        密码        角色字符串
        ------------------------------------------
        sa        sa        admin,user
        admin        admin        admin
        user        user        user
        ------------------------------------------
    测试:
        如果使用admin登录,只能访问admin目录的manager.aspx页面;
        如果使用user登录,只能访问users目录的welcome.aspx页面;
        使用sa登录,既能访问admin目录的manager.aspx页面,又能访问users目录的welcome.aspx页面。
    注意:测试时注意及时点击安全退出按钮,否则影响测试结果。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网