asp.net form验证

匿名用户不可以登陆

<authentication mode="Forms">

            <forms loginUrl="login.aspx" name=".ASPXFORMSAUTH" defaultUrl="default.aspx">
            </forms>
        </authentication>
        <authorization>
            <deny users="?"/>

        </authorization>

发动验证凭证

string roleString = role;// +"," + group;
                System.Web.Security.FormsAuthenticationTicket ticket
                        = new FormsAuthenticationTicket(2, userName, DateTime.Now, DateTime.Now.AddDays(3), true, roleString);
                string cookieString = System.Web.Security.FormsAuthentication.Encrypt(ticket);

                // 保存到 Cookie
                HttpCookie cookie = new HttpCookie(
                    System.Web.Security.FormsAuthentication.FormsCookieName);
                cookie.Value = cookieString;
                
                this.Response.Cookies.Add(cookie);
                if (Request.QueryString["returnurl"] != null)
                {
                    string returnurl = Request.QueryString["returnurl"];
                    Response.Redirect(returnurl);
                }
                else
                {
                    Response.Redirect("default.aspx");
                }

解析用户角色

void Application_PostAuthenticateRequest(object sender, EventArgs e)
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;

            if (context.User.Identity.IsAuthenticated)
            {
                // 取得用户对象
                System.Security.Principal.IPrincipal user = context.User;

                // 取得用户的角色数组
                System.Web.Security.FormsIdentity fi = user.Identity as System.Web.Security.FormsIdentity;

                // 取得用户的票据
                System.Web.Security.FormsAuthenticationTicket ticket = fi.Ticket;

                // 创建用户所拥有的角色数组
                string roleString = ticket.UserData;

                // 还原为字符串数组
                string[] roleArray = { roleString };//roleString.Split(',');


                // 自己创建用户对象
                System.Security.Principal.GenericPrincipal principal
                    = new System.Security.Principal.GenericPrincipal(
                        user.Identity,
                        roleArray
                        );
                // 让系统使用我们的拥有角色的用户对象
                context.User = principal;
            }

        }

获取用户名

  this.User.Identity.Name;

登出

FormsAuthentication.SignOut(); 

 

转载于:https://www.cnblogs.com/lantianzhishang/archive/2009/11/16/1604201.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值