ASP.NET面向角色授權之:自定義Forms使用者驗證與授權
流程
一、配置config
n 基本內容
<configuration>
<system.web>
<authenticationmode="Forms">
<formsname=".WroxDemo" loginUrl="login.aspx"protection="All" timeout="60"/>
</authentication>
<machinekey validationkey=”AutoGenerate” decrptionKey=”AutoGenerate”>//配置身份驗證的加密解密和驗證級別。
<authorization>
<denyusers="?">
</authorization>
</system.web>
</configuration>
<!—還可以配置某個目錄的許可權à
<lacatoinpath=”admin”>
<system.web>
<authorization>
<deny user=”?”>
</authorization>
</system.web>
</location>
二、填寫與匹配帳戶資訊
//從資料庫或檔案取得填寫的帳戶資訊
If(Dr.Read) //
{
//則使用者驗證通過。
{
//方式四:建立自定義身份驗證票
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "yundao", DateTime.Now,DateTime.Now.AddMinutes(30), false, "admin");
//將身份驗證票加密
string EncrTicket = FormsAuthentication.Encrypt(ticket);
//建立一個Cookie
HttpCookiemyCookie = new HttpCookie(FormsAuthentication.FormsCookieName,EncrTicket);
將Cookie寫入客戶端
Response.Cookies.Add(myCookie);
//如果Cookie被禁
If(Request.Browser.Cookies==null)
{
Session["user_name"]= TextBoxUserName.Text;
Seesion[“user_pwd”]= TextBoxPwd.Text;
}
跳轉到初始請求頁或預設頁面
//Response.Redirect(FormsAuthentication.GetRedirectUrl("yundao",false));
FormsAuthentication.RedirectFromLoginPage(txtEmail.Text,false)
}
}
三、 驗證與授權
在初始訪問頁中(比如Default.aspx)驗證與授權
If(Request.IsAuthenticated==true)//如果有訪問許可權
{
//do something
String pwd=””;
Stirng roles=””;
If(Request.Cookies[FormsAuthentication.FormsCookieName]==null)
{
Pwd = Session[“pwd”].tostring();
Roles = Session[“role”].toString();
}
Else
{
//獲得存放身份驗證票的Cookie值,這個值是經過加密的
string EncrTicket =Request.Cookies[FormsAuthentication.FormsCookieName].Value;
//獲得身份驗證票
FormsAuthenticationTicket ticket =FormsAuthentication.Decrypt(EncrTicket);
//從身份驗證票中提取經過驗證的使用者名稱
string UserName = ticket.Name;
//從身份驗證票中提取使用者資料
string UserData = ticket.UserData;
Label1.Text = UserName + ",您好!您的許可權為:" + UserData;
}
}