下面是進行角色授權的幾個基本步驟:
1.設定身份驗證方式為Forms
应用程序根目录中的Web.config中做如下设置:
< forms name = " .ASPXAUTH " loginUrl = " /login.aspx " protection = " All " timeout = " 30 " path = " / " >
</ forms >
</ authentication >
下面再對forms節點中的屬性做一些說明:
1>name: 指定完成身份验证的Http cookie的名称,默認值為.ASPAUTH,可以改成其它任意字串.
2>loginUrl: 如果未通过验证或超时后重定向的页面URL,一般为登录页面,让用户重新登录
3>Protection: 指定 cookie数据的保护方式.
可设置为: All None Encryption Validation四种保护方式
a. All表示加密数据,并进行有效性验证两种方式
b. None表示不保护Cookie.
c. Encryption表示对Cookie内容进行加密
d. validation表示对Cookie内容进行有效性验证
4>TimeOut: 指定Cookie的失效时间,單位分鐘, 超时后要重新登录.
5>path:cookie保存的位置,設定cookie時用到的路徑要與其保持一致
2.進行身份驗證,並將角色信息保存在cookie中
{
string user = this .TextBox1.Text; // 读取用户名
string password = TextBox2.Text; // 读取密码
if (Confirm(user, password) == true ) // confirm方法用来验证用户合法性的
{
string userRoles = UserToRole(user); // 调用UserToRole方法来获取role字符串
FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket( 1 , user, DateTime.Now, DateTime.Now.AddMinutes( 30 ), false , userRoles, " / " ); // 建立身份验证票对象
string HashTicket = FormsAuthentication.Encrypt(Ticket); // 加密序列化验证票为字符串
HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket);
// 生成Cookie
Context.Response.Cookies.Add(UserCookie); // 输出Cookie到客户端
Context.Response.Redirect(Context.Request[ " ReturnUrl " ]); // 重定向到用户申请的初始页面
}
else
{
// 用户身份未被确认时的代码
}
}
// 此方法用来验证用户合法性的
private bool Confirm( string user, string password)
{
// 相应的代码
}
// 此方法用来获得的用户对应的所有的role用逗号分割的一个字符串
private string UserToRole( string user)
{
// 相应的代码
}
3.在服务端將角色恢复到GenericPrincipal对象中
在Global.asax中的Application_AuthenticateRequest事件中新增以下內容
{
// 在這裡設定用戶的角色
HttpApplication App = (HttpApplication)sender;
HttpContext Ctx = App.Context; // 获取本次Http请求相关的HttpContext对象
if (Ctx.Request.IsAuthenticated == true ) // 验证过的用户才进行role的处理
{
FormsIdentity Id = (FormsIdentity)Ctx.User.Identity;
FormsAuthenticationTicket Ticket = Id.Ticket; // 取得身份验证票
string [] Roles = Ticket.UserData.Split( ' , ' ); // 将身份验证票中的role数据转成字符串数组
Ctx.User = new GenericPrincipal(Id, Roles); // 将原有的Identity加上角色信息新建一个GenericPrincipal表示当前用户,这样当前用户就拥有了role信息
}
}
4.配置權限
方法1.在每個頁面的Page_Load中判斷角色,從而分配權限.
{
// 相应的代码
}
方法2.在web.config中配置權限
1>對整個站點設定權限,在<configuration><system.web>節點下增加如下內容:
< deny users = " ? " /><!-- 拒絕匿名訪問 -->
</ authorization >
2>對目錄或單個文件設定權限,在<configuration>節點下新增以下內容:
< system.web >
< authorization >
< allow roles = " Admin " /> <!-- 只有Admin才能访问admin目录 -->
< deny users = " * " /> <!-- 拒絕所有人訪問 -->
</ authorization >
</ system.web >
</ location >
方法3.在实体上封装,具体你可以看.text asp.netforums这些优秀项目的实现