在 Web.config
設定表單驗證
<system.web>
<authentication mode="Forms">
<forms loginUrl="Login.aspx" name=".ASPXFORMSAUTH" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
<!-- 使用 sitemap -->
<siteMap defaultProvider="Def" enabled="true">
<providers>
<clear />
<add name="Def" type="System.Web.XmlSiteMapProvider" siteMapFile="..." />
<add name="Web" type="System.Web.XmlSiteMapProvider" siteMapFile="..." securityTrimmingEnabled="true" />
</providers>
</siteMap>
</system.web>
在 Global.asax
加入
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (Request.IsAuthenticated && Request.Path.EndsWith(".aspx", StringComparison.OrdinalIgnoreCase)) // 後面那個是忽略大小寫
{
FormsIdentity fi = User.Identity as FormsIdentity;
FormsAuthenticationTicket fat = fi.Ticket;
string[] roles = fat.UserData.Split(new char[] { ',' });
Context.User = new GenericPrincipal(Context.User.Identity, roles);
}
}
使用 user 登入,這段跑完就等於登入了
FormsAuthentication.RedirectFromLoginPage(user, false)
登出
FormsAuthentication.SignOut();
要取得是否登入
User.Identity.IsAuthenticated; // bool
要知道使用者是不是有某個權限
User.IsInRole("..."); // bool
這個很重要
FormsAuthentication
sample
public static void loginAuth(string user, string name, string role)
{
FormsAuthentication.RedirectFromLoginPage(user, false); // 登入的這件事
var v = 1023;
DateTime st = DateTime.Now, ed = st.AddHours(12);
var isPersistent = false;
var fatUser = new FormsAuthenticationTicket(v, name, st, ed, isPersistent, user);
var fatRole = new FormsAuthenticationTicket(v, name, st, ed, isPersistent, role);
var faeUser = FormsAuthentication.Encrypt(fatUser);
var faeRole = FormsAuthentication.Encrypt(fatRole);
HttpContext.Current.Response.Cookies.Add(new HttpCookie("login", faeUser));
HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, faeRole));
}
public static string getUserData()
{
HttpCookie login = HttpContext.Current.Request.Cookies["login"];
FormsAuthenticationTicket fatLogin = FormsAuthentication.Decrypt(login.Value);
var user = fatLogin.UserData;
return user;
}