asp.net 基于form的权限方法备忘

步骤一:

在根目录下的web.config中加入:

<system.web>

<authentication mode="Forms">
            <forms loginUrl="Login.aspx" defaultUrl="admin/admin.aspx" name=".ASPXFORMSAUTH">
            </forms>
</authentication>

</system.web>

loginUrl:用户没有登录,跳转到的登录页面

defaultUrl:正确登录之后,在没有指向页的时候,弄人跳转的页面

步骤二:

在admin文件夹下新建一个web.config文件,并加入以下代码

<system.web>
        <!--拒绝匿名用户访问此目录下的任何文件-->
        <authorization>
            <deny users="?"/>
        </authorization>
</system.web>

deny users="?":表示禁止匿名用户访问admin目录下的任何文件

到目前为止,只要你访问admin下的任何文件,都会自动跳转到Login.aspx登陆页面了,要求你先登录,否则别想看到页面。

步骤三:

在根目录下,创建Login.aspx登陆页面(可不是在admin目录下哦),加两个textbox控件一个botton控件,分别是用户名密码,和登陆按钮

双击登陆按钮,在其登陆方法里写上:

protected void btn_Login_Click(object sender, EventArgs e)
{
if (TextBox1.Text == "admin" && TextBox2.Text == "fenghua17173")
        {
            //“通知”表单验证,该用户名已经通过身份验证
            FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, true);
        }
        else
        {
            Response.Write("<script>alert('账号或密码有误,登录失败!');</script>");
        }
}

ok,这时你在login.aspx页面里填上账号密码,系统就会根据根你在根目录下web.config中配置的defaultUrl地址路径跳转过去,也就是admin/admin.aspx页面。

现在admin目录下的所有页面,均已通过身份验证,得到了可访问的票据。

也可以使用:

string user = "a";
            System.Web.Security.FormsAuthenticationTicket tk = new System.Web.Security.FormsAuthenticationTicket(1,
                    user,
                    DateTime.Now,
                    DateTime.Now.AddMinutes(3000000),
                    true,
                    "",
                    System.Web.Security.FormsAuthentication.FormsCookiePath
                    );

            string key = System.Web.Security.FormsAuthentication.Encrypt(tk); //得到加密后的身份验证票字串

            HttpCookie ck = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, key);
            HttpContext.Current.Response.Cookies.Add(ck);
            Response.Redirect("default.aspx");

最后一点:

有登陆,当然别忘了注销,这个更简单:

在admin目录下的任何一个页面中,加一个注销button按钮,并在其方法下写入:

//退出系统,注销用户
protected void btn_Logout_Click(object sender, EventArgs e)
{
//删除用户票据
        FormsAuthentication.SignOut();
        //重新定向到登陆页面
        FormsAuthentication.RedirectToLoginPage();

}

备注:

<authentication mode="Forms">

<forms loginUrl="Login.aspx"

protection="All"

timeout="30"

name="AppNameCookie"

path="/FormsAuth"

requireSSL="false"

slidingExpiration="true"

defaultUrl="default.aspx"

cookieless="UseCookies"

enableCrossAppRedirects="false"/>

</authentication>

· loginUrl 指向登录页面,你需要把它放在支持SSL的目录下

· Protection 设置成"All"表示为认证凭据同时启用数据来源验证和加密

· Timeout 指定了认证的生存时间

· name and path are set to unique values for the current application.

· requireSSL 设置成"false"表示关闭cookie的SSL加密

· slidingExpiration 如果设置成"true"的话,每次访问过期时间将会重置

· defaultUrl 就是设置程序的首页

· cookieless 设置成"UseCookies"表示使用cookie来传递认证票据

· enableCrossAppRedirects 设置成"false"表示程序不接受外部的请求

作者:黑曜石
         
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/bestfc/p/1751441.html