C# 登陆验证

Web.config

<!-- Web.config -->
<authentication mode="Forms">
    <forms name="AUTHRDB" defaultUrl="~/Account/Login.aspx" loginUrl="~/Account/Login.aspx" path="/" timeout="2880"/>
</authentication>
<authorization>
    <deny users="?"/>            <!--拒绝未认证用户,如不加此节点默认为允许所有用户访问-->
</authorization>
<sessionState configSource="Web.Session.config"/>
<location path="css">            <!-- 允许用户匿名访问css目录 -->
    <system.web>
        <authorization>
            <allow users="*"/>
        </authorization>
    </system.web>
</location>
<location path="js">            <!-- 允许用户匿名访问js目录 -->
    <system.web>
        <authorization>
            <allow users="*"/>
        </authorization>
    </system.web>
</location>

 Web.Session.config

<!-- Web.Session.config 使用数据库管理session -->
<?xml version="1.0"?>
<sessionState mode="SQLServer" allowCustomSqlDatabase="true" sqlConnectionString="Initial Catalog=LawRevision;User ID=LawRevisionUser;Password=abc_123;Data Source=10.123.4.214;" cookieless="false" timeout="200"  />

Login.aspx

protected void Login_Click(object sender, EventArgs e)
{
    User u = UserDao.GetModel(this.txtUserName.Text, this.txtPassword.Text);
    if (u == null)
    {
        lblMessage.Text = "Your username or password was not correct";
    }
    else
    {
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, u.USERNAME, DateTime.Now, DateTime.Now.AddMinutes(30), false, u.Serialize(), FormsAuthentication.FormsCookiePath);
        string hashTicket = FormsAuthentication.Encrypt(ticket);
        HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
        Response.Cookies.Add(UserCookie);
        Context.Session["PK"] = u.PK;
        Context.Session["ROLE"] = u.ROLE;
        if (Request["ReturnUrl"] != null && Request["ReturnUrl"].Length > 0)
        {
        Context.Response.Redirect(Context.Request["ReturnUrl"]);
        }
        else
        {
        Context.Response.Redirect("~/Default.aspx");
        }
    }
}

登出

System.Web.Security.FormsAuthentication.SignOut();
Response.Redirect("login.aspx");

 

posted @ 2012-09-05 16:59  Nicholas1984  阅读(369)  评论(0)    收藏  举报