摘要:[記錄] Form表單驗證紀錄
記錄使用驗證,如此以後在網頁權限上,只要透過webconfig修改即可
1.先寫webconfig
<configuration>
<connectionStrings>
<add name="default" connectionString="Data Source=USER-PC;Initial Catalog=TEST;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<!--驗證表單 如果找不到驗證cookie 會重新導向LoginUrl -->
<authentication mode="Forms">
<forms loginUrl="Login.aspx" defaultUrl="Default.aspx" name=".ASPFROMSAUTH"
protection="All" timeout="30" path="/" requireSSL="false" slidingExpiration="true"
cookieless="UseDeviceProfile" enableCrossAppRedirects="false"></forms>
</authentication>
<!--未經驗證的使用者???(以?表示) 會被拒絕存取應用程式資源-->
<authorization>
<allow roles ="Admin"/>
<deny users="?" />
</authorization>
</system.web>
</configuration>
註解:
authentication : 驗證用
authorization : 授權用
allow roles : 允許的角色 (等等會使用tickt自訂roles,所以我在webconfig使用allow roles)
allow user : 允許的名稱 (我之前就是搞錯,一直使用user,難怪不正確)
2.連db驗證帳密後,自定義tickt,並加到cookie
//自訂驗證ticket
FormsAuthenticationTicket Ticket =
new FormsAuthenticationTicket(1, user, DateTime.Now, DateTime.Now.AddMinutes(1), false, roles, "/");
//加密
string HashTicket = FormsAuthentication.Encrypt(Ticket);
//將角色加入Cookie
HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket);
HttpContext.Current.Response.Cookies.Add(userCookie);
3.我是驗證完ok,自己在login返回驗證後的頁面
Response.Redirect(FormsAuthentication.GetRedirectUrl(accountName, chkPersist.Checked));
4.Global 重新設置角色roles
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
string userData = ticket.UserData;
string[] roles = userData.Split(',');
//重建HttpContext.Current.User
HttpContext.Current.User = new GenericPrincipal(id, roles);
}
}
}
}
5.之後登入頁面就會發現沒驗證就只能看到login頁面~
參考 :