ASP.NET Forms驗證
阿新 • • 發佈:2019-01-08
/// <summary> /// 執行使用者登入操作 /// </summary> /// <param name="config">授權配置資訊</param> /// <param name="userData">與登入名相關的使用者資訊</param> /// <param name="expiration">登入Cookie的過期時間,單位:分鐘,預設120分鐘。</param> public static void SignIn(IovAuthConfig config, UserInfo userData, int expiration = 120) { if (config == null) throw new ArgumentNullException("config"); if (userData == null) throw new ArgumentNullException("userData"); if(string.IsNullOrWhiteSpace(config.AppID)) throw new ArgumentNullException("AppID"); // 1. 把需要儲存的使用者資料轉成一個字串。 string data = null; if (userData != null) data = JsonHelper.Serialize(userData); // 2. 建立一個FormsAuthenticationTicket,它包含登入名以及額外的使用者資料。 FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 2, userData.LoginID, DateTime.Now, DateTime.Now.AddDays(1), true, data); // 3. 加密Ticket,變成一個加密的字串。 string cookieValue = FormsAuthentication.Encrypt(ticket); // 4. 根據加密結果建立登入Cookie HttpCookie cookie = new HttpCookie(config.AppID, cookieValue); cookie.HttpOnly = true; cookie.Secure = FormsAuthentication.RequireSSL; cookie.Domain = FormsAuthentication.CookieDomain; cookie.Path = FormsAuthentication.FormsCookiePath; //if (expiration > 0) //預設過期時間:120分鐘 cookie.Expires = DateTime.Now.AddMinutes(expiration == 0 ? 120 : expiration); HttpContext context = HttpContext.Current; if (context == null) throw new InvalidOperationException(); // 5. 寫登入Cookie context.Response.Cookies.Remove(cookie.Name); context.Response.Cookies.Add(cookie); }
web.config同時需要修改兩個地方,如下:
<system.web> <authentication mode="Forms"> <forms name="IOV.Test" loginUrl="/" protection="All" timeout="43200" path="/" domain="" requireSSL="false" slidingExpiration="true" /> </authentication> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> </system.web>
<system.webServer> <modules runAllManagedModulesForAllRequests="true"></modules> </system.webServer>
獲取已登入使用者資訊:
/// <summary> /// 獲取當前使用者資訊 /// </summary> /// <param name="context">當前Http請求上下文</param> /// <returns></returns> public static UserInfo TryGetUserInfo(HttpContext context) { if (context == null) throw new ArgumentNullException("context"); // 1. 讀登入Cookie HttpCookie cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie == null || string.IsNullOrEmpty(cookie.Value)) return null; try { UserInfo userData = null; // 2. 解密Cookie值,獲取FormsAuthenticationTicket物件 FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); if (ticket != null && string.IsNullOrEmpty(ticket.UserData) == false) // 3. 還原使用者資料 userData = JsonHelper.Desrialize<UserInfo>(ticket.UserData); return userData; } catch { /* 有異常也不要丟擲,防止攻擊者試探。 */ } return null; }