您的位置:首页 > 其它

forms验证:怎么验证两种身份?

2007-06-19 14:56 309 查看
一、问题描述:有两种用户,买方,卖方;在数据库中分别有两个用户表。要求:网站根目录下有两个目录假设为DW目录、GR目录。目录下都

有一个login.aspx文件,分别是dwlogin.aspx,grlogin.aspx,登录时分别用自己的login.aspx文件,登录后不能访问对方的目录。

二、总体思路:创建自定义的身份验证票据,将roles信息放在票据的userData中.

三、设置Web.config
<configuration>
<system.web>
<authentication mode="Forms">
<forms name=".ASPXAUTH"
loginUrl="login.aspx"//根目录中的,就是下面的第六条
protection="All"
path="/"/>
</authentication>
</system.web>
<location path="DW">
<system.web>
<authorization>
<allow roles="DW"/>
<deny users="*" />//这里必须用*,用?达不到要求
</authorization>
</system.web>
</location>
<location path="GR">
<system.web>
<authorization>
<allow roles="GR"/>
<deny users="*" />
</authorization>
</system.web>
</location>
<location path="/DW/DWLogin.aspx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
<location path="GR/GRLogin.aspx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
四、DWLogin.aspx中

private void Button1_Click(object sender, System.EventArgs e)
{
HttpCookie objCookie;
string strReturnURL;
if (IsValid)
{
switch (GetUser( Username.Text,Password.Text))// GetUser函数得到用户名和密码,正确返回0,密码错返回2

,用户名错返回1
{
case 0:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
Username.Text,
DateTime.Now,
DateTime.Now.AddMinutes(30),
false,
"DW");//我是直接写进去的,可能还有更好的方法
objCookie = new HttpCookie( =(".ASPXAUTH" );
objCookie.Value = FormsAuthentication.Encrypt( ticket );
Response.Cookies.Add( objCookie );
strReturnURL = Request.Params[ "ReturnURL" ];
if ( strReturnURL != null )
{
Response.Redirect( strReturnURL );//返回到原来访问的页面
}
else
{
Response.Redirect( "Default.aspx" );//这里也可以设置你想设置的页面
}
break;
case 1:
this.Page.RegisterStartupScript("Info","<script>alert('该用户不存在!!');</script>");
break;
case 2:
this.Page.RegisterStartupScript("Info","<script>alert('密码错误!!');</script>");
break;
}
}
}

个人的登录页面GRLogin.aspx中写法同上面

五、Global.asax中添加如下代码:

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id =(FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new GenericPrincipal(id, roles);
}
}
}
}

六、根目录下建login.aspx,其中添加如下代码:(这个login.aspx没有用户名和密码输入框,主要是用来重定位各自的登录页面)

private void Page_Load(object sender, System.EventArgs e)
{
string ParamName = "ReturnUrl";
string ReturnUrl = Request.QueryString[ParamName];
if (ReturnUrl.ToLower().IndexOf("DW") >=0)
{
Response.Redirect("DW/DWLogin.aspx?" + ParamName + "=" + ReturnUrl);
}
else if (ReturnUrl.ToLower().IndexOf("GR") >=0 )
{
Response.Redirect("GR/GRLogin.aspx?" + ParamName + "=" + ReturnUrl);
}
else
{
//这里添加一些你的提示,指定页面也可以
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: