Form验证之简单应用

本文详细阐述了在Web应用中创建不同权限的文件夹、配置Web.config以实现基于角色的认证,并通过序列化与反序列化来管理用户信息的过程。包括使用BasePage作为基类继承页面、定义LoginInfo类进行用户信息存储、以及实现序列化与反序列化的具体代码。同时介绍了如何通过Forms Authentication实现自动与手动登录,以及如何在页面中获取登录用户的权限信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1,创建四个文件夹 Admin AdminFolder,DataClass,UserFolder。

Admin:登录以及注册页面

AdminFolder:放入拥有Admin权限的页面

UserFolder:放入拥有User权限的页面

DataClass:Serialize.cs  序列化以及反序列化

                 LoginInfo.cs:存入登录信息

                 BasePage.cs  每个页面所要继承取值的类

2,创建一些Web.config

AdminFolder下的config:

<?xml version="1.0"?>
<configuration>
    <system.web>
        <authorization>
            <allow roles="Admin"/>
            <deny users="*"/>
        </authorization>
    </system.web>
</configuration>


roles为Admin,如果没有权限,拒绝一切用户。

UserFolder同理。

根目录下Config:

<authentication mode="Forms">
            <forms loginUrl="Admin/Login.aspx" timeout="20" path="/" protection="All" />
        </authentication>

    <location path="Admin/Register.aspx">
        <system.web>
            <authorization>
                <allow users="*"/>
            </authorization>
        </system.web>
    </location>


 

location写为regist.aspx,代表不限制注册页用户。

loginUrl:默认登录页面。

3,一些代码:

BasePage.cs:

public class BasePage:Page
    {
        public LoginInfo LoginUser
        {
            get
            {
                //从票据中返回UserData,并反序列化为对象
                string strUser = ((FormsIdentity)this.Context.User.Identity).Ticket.UserData;
                return Serialize.DnSerializeFun(strUser);
            }
        }
    }


LoginInfo.cs:

[Serializable]
    public class LoginInfo
    {
        public int id { get; set; }
        public string Name { get; set; }
        public DateTime LoginTime { get; set; }
        public string Roles { get; set; }
    }


 

Serializable代表可被序列化。

Serialize.cs:

//对象序列化为字符串
        public string SerializeFun(LoginInfo Li)
        {
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            bf.Serialize(ms, Li);
            byte[] objbyte = ms.ToArray();
            return Convert.ToBase64String(objbyte, 0, objbyte.Length);
        }
        //字符串序列化为对象
        public  static LoginInfo DnSerializeFun(string SerializeStr)
        {
            byte[] byt = Convert.FromBase64String(SerializeStr);
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream ms = new MemoryStream(byt, 0, byt.Length);
            return bf.Deserialize(ms) as LoginInfo;           
        }


Global.asax:

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            if (this.Context.User != null)
            {
                if (this.Context.User.Identity.IsAuthenticated)
                {
                    if (this.Context.User.Identity is FormsIdentity)
                    {
                        string strUser = ((FormsIdentity)this.Context.User.Identity).Ticket.UserData;

                        string[] roles = DataClass.Serialize.DnSerializeFun(strUser).Roles.Split(',');

                        this.Context.User = new GenericPrincipal(this.Context.User.Identity, roles);
                    }
                }
            }
        }


 

GenericPrincipal:用户属于哪个权限

两种登录方法:

//自动设置Ticket
        private void AutoLogin()
        {
            FormsAuthentication.SetAuthCookie(TextBox1.Text, false);
            Response.Redirect("Main.aspx"); 

        }
        //手动设置Ticket
        private void TicketLogin()
        {
            LoginInfo dl = new LoginInfo();
            Serialize sr = new Serialize();

            if (TextBox1.Text == "123" && TextBox2.Text == "123")
            {
                //LoginInfo赋值
                dl.id = 1;
                dl.Name = TextBox1.Text;
                dl.LoginTime = DateTime.Now;

                //判断什么Roles,用,分开
                dl.Roles = "User,Admin";
                //序列化LoginInfo
                string SeStr = sr.SerializeFun(dl);

                //定义ticket
                FormsAuthenticationTicket ft = new FormsAuthenticationTicket(1, "Admin", DateTime.Now, DateTime.Now.AddMinutes(20), false, SeStr);

                //加密ticket
                string strTicket = FormsAuthentication.Encrypt(ft);

                //使用userdata保存cookie
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strTicket);
                cookie.Expires = ft.Expiration;
                Response.Cookies.Add(cookie);
                Response.Redirect("../AdminFolder/AdminPage.aspx");
            }
            else
            {
                Response.Write("密码错误");
            }
        }


页面取值:

public partial class UserPage : DataClass.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write(LoginUser.Roles);
        }
    }


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值