先要建一個asp.net應用程序,這裏面至少要有一個登錄用的頁面,然後修改你的根目錄下的web.config,把驗證那一塊改成Forms驗證模式。
<forms loginUrl="Login.aspx" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
<system.web>
<authorization>
<!--設置准許訪問此文件夾的角色和拒絕的角色,這裏准許管理員,老師訪問,拒絕學生訪問-->
<allow roles="admin" />
<allow roles="teacher" />
<deny roles="student" />
<!--前提是拒絕匿名用戶!-->
<deny users="?" />
</authorization>
</system.web>
</configuration>
如下:此設置是保護admin文件夾下的內容,拒絕匿名用戶訪問
<system.web>
<authorization>
<deny users="?"></deny>
</authorization>
</system.web>
</location>
有兩種方式,第一種,當網站的用戶不是很多的時候,可以把用戶和密碼放到web.config裏。辦法就是在根目錄下的web.config文件中加入一個credentials節,裏面寫上用戶名和密碼,這個是包含在forms節裏面的。
如下所示:
<forms loginUrl="login.aspx">
<credentials passwordFormat="Clear">
<user name="admin" password="admin"/>
</credentials>
</forms>
</authentication>
下面着重介紹第二種方法,通過數據庫讀取用戶名密碼進行驗證。
1:首先在數據庫裏建立三張表: Users(UserID,UserName,UserPwd)---存放用戶信息
Roles(RoleID,RoleName)------存放角色名稱
User_Role(UserID,RoleID)-----用戶和角色的中間表,使頭兩張表成爲多對多關係
2:然後在登陸頁面的登陸按鈕點擊事件中加入如下邏輯
{
if(Users.Authenticate(txtUsername.Text, txtPassword.Text))//數據庫驗證方法,代碼略
{
//驗證後導向初始頁
FormsAuthentication.RedirectFromLoginPage( txtUsername.Text, chkRemember.Checked ;
}
}
3:然後就要用到global.asax文件下的Application_AuthenticateRequest事件了,此事件在每次訪問aspx文件都會觸發。
在其中加入如下代碼,功能見註釋:
{
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);
}
}
詳細碼略,這裏主要爭對三張表寫出獲得用戶角色的存儲過程
(
@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