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
}
}