`
白玉水堂
  • 浏览: 14604 次
  • 性别: Icon_minigender_1
  • 来自: 广州
最近访客 更多访客>>
社区版块
存档分类
最新评论

ASP.NET内置票据认证的使用

 
阅读更多
ASP.NET内置票据认证

根据你的设置,在进入到某一个目录下的页面时自动判断你是否有权限访问这个页面,没有权限则自动跳转到你预先设置的登录页
1、 在根目录建立一个Global.asax文件,复制如下一段代码
    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 tiecket = id.Ticket;
                    string userData = tiecket.UserData;
                    string[] roles = userData.Split(',');
                    HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);
                }
            }
        }
    }

2、 在web.config 文件中配置目录权限及登录页,
登录页,在system.web节点中
<authentication mode="Forms">
            <forms name="mycook" loginUrl="login.aspx" protection="All" path="/"/>
</authentication>
配置目录权限,在system.web节点外面
<location path="admin">
        <system.web>
            <authorization>
                <allow roles="admin"/>
                <deny users="*"/>
            </authorization>
        </system.web>
    </location>
    <location path="user">
        <system.web>
            <authorization>
                <allow roles="user"/>
                <deny users="*"/>
            </authorization>
        </system.web>
    </location>
    <location path="admin/admin_login.aspx">
        <system.web>
            <authorization>
                <allow users="*"/>
            </authorization>
        </system.web>
    </location>
    <location path="user/user_login.aspx">
        <system.web>
            <authorization>
                <allow users="*"/>
            </authorization>
        </system.web>
    </location>

3、 在登录页的登录事件中的登录成功后烤入一段代码
  HttpCookie cook;
            string strReturnURL;
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                1, name, DateTime.Now, DateTime.Now.AddMinutes(30), false, lv);
            cook = new HttpCookie("mycook");
            cook.Value = FormsAuthentication.Encrypt(ticket);
            Response.Cookies.Add(cook);
            strReturnURL = Request.Params["ReturnUrl"];
            if (strReturnURL != null)
            {
                Response.Redirect(strReturnURL);
            }
            else
            {
                Response.Redirect("Default.aspx");
            }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics