使用FormsAuthentication

FormsAuthentication是微软为RBAC(基于角色的访问控制)提供的一个重要类,如何使用这么一个类?

这里先要介绍一下配置节

首先要把站点主Web.config 中的配置节改为<authentication mode="Forms">

其次在需要控制访问的目录下建立Web.config

<system.web>
      <authorization >
        <deny users="?"/>
      </authorization>
    </system.web>

在Web.config里面加入这么一个节点后 Web.config所在控制域的页面就不能被未登录用户访问

 

在使用了自定义的认证方法后 设置验证票就可以访问了

代码如下

if(DataBaseCheck(userid,pwd))

     FormsAuthentication.SetAuthCookie(userid);

 

DataBaseCheck是我们自己的验证法则,对参数用户名和密码做验证,通过则返回true

如果需要登录回转的话可以用FormsAuthentication.RedirectFromLoginPage(userid,false);

 

其实如果要有更细粒度的控制 可以这么来

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(userid, false, 3000);
Response.Cookies[FormsAuthentication.FormsCookieName].Value = FormsAuthentication.Encrypt(ticket);

数字3000为登录timeout数字

 

如果文件夹没有配置Web.config的authorization,那么在登录后的页面里 判定是否认证可以通过User.Identity.IsAuthenticated

登录后的userid可以通过User.Identity.Name获得。

 

如果需要在页面保存更多user信息 可以做一个UserProfile类在数据库获取,假设UserInfo为用户信息实体,

class UserProfile

{

      public UserInfo LoginUserInfo

      {

            get

            {

                 UserInfo user = Session["userinfo"] as UserInfo
                 if(user == null)
                 {
                     user = BizLayer.GetUserInfo(userid);
                     Session["userinfo"] = user
                }
                 return user

            }

}

 

 

### 在 Visual Studio 中使用 FormsAuthentication 实现登录功能 #### 1. 配置 Web.config 文件 为了启用 FormsAuthentication 功能,需要在项目的 `Web.config` 文件中进行相应的配置。以下是一个典型的配置示例: ```xml <configuration> <system.web> <authentication mode="Forms"> <forms loginUrl="~/Account/Login.aspx" timeout="30" protection="All" /> </authentication> <authorization> <deny users="?" /> <allow users="*" /> </authorization> </system.web> </configuration> ``` 上述配置设置了表单身份验证模式,并指定了登录页面的位置以及超时时间[^1]。 --- #### 2. 创建登录页面 (Login.aspx) 在登录页面中放置一个用于接收用户名和密码的表单。例如: ```html <form id="form1" runat="server"> <div> 用户名:<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox><br /> 密码:<asp:TextBox ID="txtPassword" TextMode="Password" runat="server"></asp:TextBox><br /> <asp:Button ID="btnLogin" runat="server" Text="登录" OnClick="btnLogin_Click" /><br /> <asp:Label ID="lblMessage" runat="server" ForeColor="Red"></asp:Label> </div> </form> ``` --- #### 3. 编写后台代码以处理登录请求 在登录按钮点击事件中,验证用户输入的凭据是否正确。如果验证通过,则调用 `FormsAuthentication.SetAuthCookie()` 方法设置身份验证 Cookie 并执行页面跳转。 ```csharp using System.Web.Security; protected void btnLogin_Click(object sender, EventArgs e) { string username = txtUsername.Text.Trim(); string password = txtPassword.Text.Trim(); if (ValidateUser(username, password)) { FormsAuthentication.SetAuthCookie(username, false); // 设置身份验证 Cookie Response.Redirect("~/NextPage.aspx"); // 跳转到目标页面 } else { lblMessage.Text = "用户名或密码不正确"; // 显示错误消息 } } private bool ValidateUser(string username, string password) { return username.Equals("guest", StringComparison.OrdinalIgnoreCase) && password.Equals("rcqzyy"); } ``` 以上代码实现了简单的硬编码验证逻辑。对于生产环境,建议采用数据库或其他安全的方式存储用户凭据并进行加密处理[^2]。 --- #### 4. 受保护页面的安全性配置 为了让某些页面仅限已登录用户访问,可以在 `Web.config` 文件中针对这些页面添加授权规则。例如: ```xml <location path="NextPage.aspx"> <system.web> <authorization> <allow users="*" /> <!-- 允许所有已登录用户 --> <deny users="?" /> <!-- 拒绝匿名用户 --> </authorization> </system.web> </location> ``` 这样可以确保未经授权的用户无法直接访问受保护的页面[^3]。 --- #### 5. 注销功能实现 除了登录外,通常还需要提供注销的功能。可以通过清除当前用户的认证状态来实现这一点: ```csharp protected void LogoutButton_Click(object sender, EventArgs e) { FormsAuthentication.SignOut(); // 清除身份验证 Cookie Session.Abandon(); // 结束会话 Response.Redirect("~/Account/Login.aspx"); // 返回登录页 } ``` --- ### 总结 通过上述步骤,即可在 Visual Studio 中利用 FormsAuthentication 构建完整的登录机制。该方案涵盖了从基础配置到具体实现细节的过程,适用于中小型应用项目中的用户身份管理需求[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值