<authentication mode="Forms">
<forms loginUrl="Login.aspx" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
<configuration>
<system.web>
<authorization>
<!--设置准许访问此文件夹的角色和拒绝的角色,这里准许管理员,老师访问,拒绝学生访问-->
<allow roles="admin" />
<allow roles="teacher" />
<deny roles="student" />
<!--前提是拒绝匿名用户!-->
<deny users="?" />
</authorization>
</system.web>
</configuration>
<location path="admin">
<system.web>
<authorization>
<deny users="?"></deny>
</authorization>
</system.web>
</location>
<authentication mode="Forms" >
<forms loginUrl="login.aspx">
<credentials passwordFormat="Clear">
<user name="admin" password="admin"/>
</credentials>
</forms>
</authentication>
if (Page.IsValid)
{
if(Users.Authenticate(txtUsername.Text, txtPassword.Text))//数据库验证方法,代码略
{
//验证后导向初始页
}
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if (Request.IsAuthenticated == true) //如果验证了用户,则为 true,否则为 false
{
String[] roles;
// 首次登陆,还没有存入角色cookies
if ((Request.Cookies["userlroles"] == null) || (Request.Cookies["userlroles"].Value == "")) 
{
// 此时调用方法,访问数据库中的记录获得用户角色,并存入cookies
roles =(String[]) Users.GetRoles(User.Identity.Name).ToArray(typeof(String));
String roleStr = "";
foreach (String role in roles) //一个用户会有多种角色,以一个字符串表示,用;隔开
{
roleStr += role;
roleStr += ";";
}
//创建cookies票据
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, //版本
Context.User.Identity.Name, //登陆时候存入的标识用户的用户名
DateTime.Now, // 发布时间
DateTime.Now.AddHours(1), // 过期时间
false, // 是否持久
roleStr // 角色字符串
);
// 加密票剧
String cookieStr = FormsAuthentication.Encrypt(ticket);
//发送到客户端,起名userroles
Response.Cookies["userroles"].Value = cookieStr;//必须加密
Response.Cookies["userroles"].Path = "/";
Response.Cookies["userroles"].Expires = DateTime.Now.AddMinutes(1);
}
else 
{
// 已存在,读取,解密
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies["userroles"].Value);
//把角色字符添加到list里
ArrayList userRoles = new ArrayList();
foreach (String role in ticket.UserData.Split( new char[] {';'} )) 
{
userRoles.Add(role);
}
roles = (String[]) userRoles.ToArray(typeof(String));
}
// 把此用户的角色存到内存中,可以运用User.IsInRole()方法进行检验用户角色
// 也可以使用实现IPrincipal接口的类,自定义赋值给Context.User
Context.User= new GenericPrincipal(Context.User.Identity, roles);
}
}
CREATE PROCEDURE User_GetUserRolesByUsername
(
@Username nvarchar(50)
)
AS
select Roles.RoleName
from Roles
join Users on Users.Username=@Username
join User_Role on User_Role.UserID=Users.UserID
where Roles.RoleID=User_Role.RoleID
GO发表于 @ 2006年05月20日 17:09:00 | 评论( loading... ) | 举报| 收藏